为了账号安全,请及时绑定邮箱和手机立即绑定

请教关于在c#中不使用Replace(),而实现替换的问题!

请教关于在c#中不使用Replace(),而实现替换的问题!

一只甜甜圈 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();

}



查看完整回答
反对 回复 2022-02-28
?
杨__羊羊

TA贡献1943条经验 获得超7个赞

很简单,替换"=top"为"=x";"=left"为"=y"

查看完整回答
反对 回复 2022-02-28
  • 2 回答
  • 0 关注
  • 293 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号