你应该注意到,在很大程度上取决于你如何定义“空白”。 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