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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

参考技术A

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


参考技术B 嗯,字符串的Replace()方法应该可以帮你:(返回均是字符串)
string str=textBox.Text.Replace("111", "ggg");//替换字符串,也可以是一个字符,但是需要用双引号

string str= textBox.Text.Replace('f','g');//替换单个字符
试试吧本回答被提问者采纳
参考技术C string a = new string();
...//这里设置字符串a的值

//查找"string"并删除
int i = a.IndexOf("string");
a=a.Remove(i, "string".Length); // 结果在返回值中
参考技术D 用replace方法 将字符串中要删除的字符替换为空就好了

以上是关于c#如何把字符串中的指定字符删除的主要内容,如果未能解决你的问题,请参考以下文章

python如何删除字符串中指定位置的字符

SQL如何将一列表中的字符替换成另外一个字符

在程序中如何去掉字符串中的空字符

急!如何批量删除数据库中以特定字符开头和结尾的字符串

如何对输入的指定个数的字符串进行按字典序排序?

python中如何去掉字符串的空格