c#如何把字符串中的指定字符删除

 我来答
惠企百科
2022-11-15 · 百度认证:北京惠企网络技术有限公司官方账号
惠企百科
惠企百科网是一家科普类综合网站,关注热门中文知识,集聚互联网精华中文知识,本着自由开放、分享价值的基本原则,向广大网友提供专业的中文知识平台。
向TA提问
展开全部

string s = "abc";

int len = s.Length;

char[] s2 = new char[len];

int i2 = 0;

for (int i = 0; i < len; i++)

{

char c = s[i];

if (c != '\r' && c != '\n' && c != '\t')

s2[i2++] = c;

}

return new String(s2, 0, i2);

扩展资料:

C#常用的字符串操作方法:替换、删除、拆分字符串

1、C#替换字符串):

public string Replace(char oldChar,char newChar); 在对象中寻找oldChar,如果寻找到,就用newChar将oldChar替换掉。

如:

string st = "abcdef";

string newstring = st.Replace('a', 'x');

Console.WriteLine(newstring);   //即:xbcdef

2、Remove(C#删除字符串):

public string Remove(int startIndex); 从startIndex位置开始,删除此位置后所有的字符(包括当前位置所指定的字符)。

如:  

string st = "abcdef";

string newstring = st.Remove(4);

Console.WriteLine(newstring);  //即:abcd

3、Substring(C#字符串截取):

public string Substring(int startIndex); 从startIndex位置开始,提取此位置后所有的字符(包括当前位置所指定的字符)。

如:  

string st = "abcdef";

string newstring = st.Substring(2);

Console.WriteLine(newstring);  //即:cdef

public string Substring(int startIndex,int count); 从startIndex位置开始,提取count个字符。
如:  

string st = "abcdef";

string newstring = st.Substring(2,2);

Console.WriteLine(newstring);  //即:cd

4、Split(C#拆分字符串)

public string[] Split ( params char[] separator ):根据separator 指定的没有字符分隔此实例中子字符串成为Unicode字符数组, separator可以是不包含分隔符的空数组或空引用。

public string[] Split ( char[] separator, int count ):参数count 指定要返回的子字符串的最大数量。 

如:

string st = "语文|数学|英语|物理";

string[] split = st.Split(new char[]{'|'},2);

for (int i = 0; i < split.Length; i++)

{

Console.WriteLine(split[i]);

}

已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式