当前位置:首页 > windos > 正文

C#常规字符串处理

 1用Reverse方法反转一个字符串

1
2
3
string  funnyMan = "Roscoe Arbuckle";
string  backwardsGuy = new string(funnyMan.Reverse().ToArray());
//backwardsGuy="elkcubrA eocsoR";

2. 使用String.Split把字符串分割成子字符串

1
2
3
4
5
6
7
string  names = "John,Mary,Elvis,Ringo";//names = "John,Mary,Elvis,Ringo?I‘m fine";
//Split参数是数组,所以可以多个字符作为分隔符
string [] nameList = names.Split( new  char[] { ‘,‘});//new char[] { ‘,‘,‘?‘,‘\‘‘,‘ ‘}
Console.WriteLine(nameList[0]);  // John
Console.WriteLine(nameList[1]);  // Mary
Console.WriteLine(nameList[2]);  // Elvis
Console.WriteLine(nameList[3]);  // Ringo

 

也可以使用循环来遍历string数组
1
2
3
4
5
6
7
8
string  names = "John - Mary - Elvis - Ringo";
// Same result as before - we get four names, without spaces or dash
string [] nameList = names.Split( new  string[] { " - " },
StringSplitOptions.RemoveEmptyEntries);
foreach  (string str in nameList)
{
Console.WriteLine(str);
}
参数指定移除空格

3.字符串函数连在一起操作

1
2
3
4
char [] braces =  new  char[] { ‘{‘, ‘}‘ };
string  s = "{This|That|Such}";
s = s.Replace( "|" ,  " and " ).Trim(braces).Insert(0,  "=> " ).ToLower();
Console.WriteLine(s);  // => this and that and such

可以将操作的字符串的函数在一行中实现

4. 通过Trim方法在字符串中减少前导和尾随字符

1
2
string  s = " The core phrase"; // 2 leading spaces, 1 trailing
s = s.Trim();  // s = "The core phrase"
注意:(1)Trim()方法默认只是去掉开头和结尾的空格,不会去掉字符串中间的空格。
    (2)任何对字符串的操作,都不改变原字符串的值,都会返回一个新的实例,需要赋值给一个变量,才能得到对字符串操作结果的字符串。
  • 也可以给Trim()方法附加参数,指定要截去的字符

1
2
3
4
string  s = " {The core phrase,} ";
s = s.Trim( new  char[] { ‘ ‘, ‘{‘, ‘,‘, ‘}‘ });// s = "The core phrase"
s =  " {Doesn‘t {trim} internal stuff }" ;
s = s.Trim( new  char[] { ‘ ‘, ‘{‘, ‘}‘ });// s = "Doesn‘t {trim} internal stuff"
 
  • 也可以通过TrimStart和 TrimEnd方法截去字符串的开头和结尾

1
2
3
4
string  s = "{Name}";
char [] braces =  new  char[] { ‘{‘, ‘}‘ };
string  s2 = s.TrimStart(braces); // s2 = "Name}"
string  s3 = s.TrimEnd(braces); // s3 = "{Name"

5. 插入和移除子字符串

可以通过String.Insert方法在一个字符串的任何位置插入一个子字符串。

1
2
3
string  s = "John Adams";
int  n = s.IndexOf("Adams");
s = s.Insert(n,  "Quincy " );  // s now "John Quincy Adams"

 

注意:字符串时不可变的,即使调用Insert方法,如果未把操作的结果赋给任何变量,对原字符串没有任何影响。

1
2
string  s = "John Adams";
s.Insert(5,  "Quincy " );  // Allowed, but s is not changed

可以通过String.Remove方法指定下标开始,指定长度的子字符串,字符串的下标从0开始。

1
2
string  s = "OHOLEne";
s = s.Remove(1, 4);  // Start at position 1, remove 4 characte