c#如何把字符串中的指定字符删除
2022-11-15 · 百度认证:北京惠企网络技术有限公司官方账号
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]);
}