一只甜甜圈
2022-02-25 19:15:28
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
提交
取消