如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
当前回答
许多答案都提供了正确的输出,但对于那些寻找最佳性能的人来说,我确实将Nolanar的答案(性能的最佳答案)提高了大约10%。
public static string MergeSpaces(this string str)
{
if (str == null)
{
return null;
}
else
{
StringBuilder stringBuilder = new StringBuilder(str.Length);
int i = 0;
foreach (char c in str)
{
if (c != ' ' || i == 0 || str[i - 1] != ' ')
stringBuilder.Append(c);
i++;
}
return stringBuilder.ToString();
}
}
其他回答
string sentence = "This is a sentence with multiple spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");
我可以用这个删除空格
while word.contains(" ") //double space
word = word.Replace(" "," "); //replace double space by single space.
word = word.trim(); //to remove single whitespces from start & end.
我认为Matt的答案是最好的,但我不认为它是完全正确的。如果你想替换换行符,你必须使用:
myString = Regex.Replace(myString, @"\s+", " ", RegexOptions.Multiline);
其实比这简单得多:
while(str.Contains(" ")) str = str.Replace(" ", " ");
许多答案都提供了正确的输出,但对于那些寻找最佳性能的人来说,我确实将Nolanar的答案(性能的最佳答案)提高了大约10%。
public static string MergeSpaces(this string str)
{
if (str == null)
{
return null;
}
else
{
StringBuilder stringBuilder = new StringBuilder(str.Length);
int i = 0;
foreach (char c in str)
{
if (c != ' ' || i == 0 || str[i - 1] != ' ')
stringBuilder.Append(c);
i++;
}
return stringBuilder.ToString();
}
}