using System;class Program{static void Main(){string s = "abcdeabcdeabcde";string str = "cd";string s1 = "x";string result;string[] sArray1 = s.Split(str.ToCharArray());foreach (string i in sArray1){result = i+s1 ;Console.Write(result);}}}我想把cd替换成x,让结果输出为abxeabxeabxe,但是使用Split()却变成了abxxeabxxeabxxe;请问应该如何修改?或者还有其他方法吗?请问输出后最后位还有个X,怎么去掉。就是说输出后是abxeabxeabxex,在最后位多了个x,要如何修改下,不出现x?另一个问题,如果我是修改ab而不是cd,输出结果是cdexcdexcdex,而不是xcdexcdexcde,除了将 result = i+s1 ;改为 result =s1+i ;还有没有更好点的方法?谢谢
2 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
下面是使用split()的方法:
static void Main(string[] args)
{
string s1 = "abcdeabcdeabcde";
string[] array = s1.Split('c', 'd');
string s2 = null;
int i = -1;
foreach (string s3 in array)
{
i++;
if (s3 == "")
{
s2 = s2 + "x";
i++;
}
else
{
s2 = s2 + s3;
}
}
Console.WriteLine(s2);
Console.ReadKey();
}
下面是不使用split()的方法:
static void Main(string[] args)
{
string s1 = "abcdeabcdeabcde";
string s2 = null;
int i = -1;
bool flag = false;
foreach (char c in s1)
{
if (flag == true)
{
flag = false;
continue;
}
i++;
if (c == 'c'&& s1[i + 1] == 'd')
{
s2 = s2 + "x";
i ++;
flag = true;
}
else
{
s2 = s2 + c;
}
}
Console.WriteLine(s2);
Console.ReadKey();
}
添加回答
举报
0/150
提交
取消
