如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
如何用c#中的一个空格替换字符串中的多个空格?
例子:
1 2 3 4 5
是:
1 2 3 4 5
当前回答
要不耍流氓?
public static string MinimizeWhiteSpace(
this string _this)
{
if (_this != null)
{
var returned = new StringBuilder();
var inWhiteSpace = false;
var length = _this.Length;
for (int i = 0; i < length; i++)
{
var character = _this[i];
if (char.IsWhiteSpace(character))
{
if (!inWhiteSpace)
{
inWhiteSpace = true;
returned.Append(' ');
}
}
else
{
inWhiteSpace = false;
returned.Append(character);
}
}
return returned.ToString();
}
else
{
return null;
}
}
其他回答
string sentence = "This is a sentence with multiple spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");
根据Joel的说法,巩固其他答案,并希望随着我的前进略有改善:
你可以用Regex.Replace()来实现:
string s = Regex.Replace (
" 1 2 4 5",
@"[ ]{2,}",
" "
);
或者使用String.Split():
static class StringExtensions
{
public static string Join(this IList<string> value, string separator)
{
return string.Join(separator, value.ToArray());
}
}
//...
string s = " 1 2 4 5".Split (
" ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries
).Join (" ");
我仔细查看了建议的解决方案,但没有找到一个可以处理我的情况下可接受的空白字符的混合,例如:
正则表达式。Replace(input, @"\s+", " " ") -它将吃掉你的换行符,如果它们与空格混合,例如\n \n序列将被替换为 正则表达式。Replace(source, @"(\s)\s+", "$1") -它将依赖于空格的第一个字符,这意味着它可能再次吃掉你的换行符 正则表达式。Replace(source, @"[]{2,}", " ") -当有混合空白字符时,它将无法正常工作-例如"\t \t "
可能并不完美,但对我来说快速的解决方法是:
Regex.Replace(input, @"\s+",
(match) => match.Value.IndexOf('\n') > -1 ? "\n" : " ", RegexOptions.Multiline)
思想是换行胜过空格和制表符。
这不会正确地处理窗口换行,但它也很容易调整工作,不知道正则表达式那么好-可能是有可能适合单一模式。
您可以简单地在一行解决方案中做到这一点!
string s = "welcome to london";
s.Replace(" ", "()").Replace(")(", "").Replace("()", " ");
如果喜欢,可以选择其他括号(甚至其他字符)。
使用正则表达式模式
[ ]+ #only space
var text = Regex.Replace(inputString, @"[ ]+", " ");