你應該注意到,在很大程度上取決於你如何定義「空白」。 Unicode和CLR將空白字符定義爲a rather exhaustive list of characters:char.IsWhitespace()
對於很多字符都返回true。
空白的「經典」定義是以下字符:HT,LF,VT,FF,CR和SP(有些可能還包括BS)。
我自己,我可能會做這樣的事情:
public static class StringHelpers
{
public static string StripWhitespace(this string s)
{
StringBuilder sb = new StringBuilder() ;
foreach (char c in s)
{
switch (c)
{
//case '\b' : continue ; // U+0008, BS uncomment if you want this
case '\t' : continue ; // U+0009, HT
case '\n' : continue ; // U+000A, LF
case '\v' : continue ; // U+000B, VT
case '\f' : continue ; // U+000C, FF
case '\r' : continue ; // U+000D, CR
case ' ' : continue ; // U+0020, SP
}
sb.Append(c) ;
}
string stripped = sb.ToString() ;
return stripped ;
}
}
你可以使用正是如此你的方法。然而,這對READ THE DOCUMENTATION重要):你會注意到使用string
構造函數重載,讓您的數組作爲字符串初始化向量中指定一個範圍:
public static string StripWhitespace(string s)
{
char[] buf = s.ToCharArray() ;
int j = 0 ; // target pointer
for (int i = 0 ; i < buf.Length ; ++i)
{
char c = buf[i] ;
if (!IsWs(c))
{
buf[j++] = c ;
}
}
string stripped = new string(buf,0,j) ;
return stripped ;
}
private static bool IsWs(char c)
{
bool ws = false ;
switch (c)
{
//case '\b' : // U+0008, BS uncomment if you want BS as whitespace
case '\t' : // U+0009, HT
case '\n' : // U+000A, LF
case '\v' : // U+000B, VT
case '\f' : // U+000C, FF
case '\r' : // U+000D, CR
case ' ' : // U+0020, SP
ws = true ;
break ;
}
return ws ;
}
你也可以使用LINQ的,東西像:
public static string StripWhitespace(this string s)
{
return new string(s.Where(c => !char.IsWhiteSpace(c)).ToArray()) ;
}
雖然,我願意Linq的方法會明顯慢於其他兩個。雖然它很優雅。
我想你的意思是說'source [newIndex] ='\ 0'' – AndyG
@AndyG:這將避免IndexOutOfRangeException,但它不會截斷字符串。 –
該代碼導致大量的更正 – prabhakaran