如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
当前回答
您可以简单地在一行解决方案中做到这一点!
string s = "welcome to london";
s.Replace(" ", "()").Replace(")(", "").Replace("()", " ");
如果喜欢,可以选择其他括号(甚至其他字符)。
其他回答
我可以用这个删除空格
while word.contains(" ") //double space
word = word.Replace(" "," "); //replace double space by single space.
word = word.trim(); //to remove single whitespces from start & end.
我喜欢用:
myString = Regex.Replace(myString, @"\s+", " ");
因为它将捕获任何类型的空白(例如制表符,换行符等)的运行,并将它们替换为单个空格。
我认为Matt的答案是最好的,但我不认为它是完全正确的。如果你想替换换行符,你必须使用:
myString = Regex.Replace(myString, @"\s+", " ", RegexOptions.Multiline);
下面的代码将所有多个空格删除为一个空格
public string RemoveMultipleSpacesToSingle(string str)
{
string text = str;
do
{
//text = text.Replace(" ", " ");
text = Regex.Replace(text, @"\s+", " ");
} while (text.Contains(" "));
return text;
}
string xyz = "1 2 3 4 5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));