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

如题所述

可以使用以下四种方法:

一、使用关键字:Replace

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

1、实例代码:

2、执行结果:

二、Remove(C#删除字符串)

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

示例代码:

三、Substring(C#字符串截取)

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

示例代码:

四、Trim(C#清空空格):

public string Trim ():将字符串对象包含的字符串两边的空格去掉后返回。

public string Trim ( params char[] trimChars ): 从此实例的开始和末尾移除数组中指定的一组字符的所有匹配项。

示例代码如下:

参考资料:

百度百科--substring

微软文档中心--replace

微软文档中心--remove

微软文档中心--String.Trim Method

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2019-08-14

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]);

}

本回答被网友采纳
第2个回答  推荐于2016-02-07
嗯,字符串的Replace()方法应该可以帮你:(返回均是字符串)
string str=textBox.Text.Replace("111", "ggg");//替换字符串,也可以是一个字符,但是需要用双引号

string str= textBox.Text.Replace('f','g');//替换单个字符
试试吧本回答被提问者采纳
第3个回答  2010-05-17
string a = new string();
...//这里设置字符串a的值

//查找"string"并删除
int i = a.IndexOf("string");
a=a.Remove(i, "string".Length); // 结果在返回值中
第4个回答  2010-05-17
用replace方法 将字符串中要删除的字符替换为空就好了

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网