如何在C#中只用一个空格替换字符串中的多个空格?
例:
1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)
将会:
1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)
Mat*_*att 589
我喜欢用:
myString = Regex.Replace(myString, @"\s+", " ");
Run Code Online (Sandbox Code Playgroud)
因为它将捕获任何类型的空格(例如制表符,换行符等)的运行并用单个空格替换它们.
Pat*_*ins 434
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
tempo = regex.Replace(tempo, " ");
Run Code Online (Sandbox Code Playgroud)
tva*_*son 45
string xyz = "1 2 3 4 5";
xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
Run Code Online (Sandbox Code Playgroud)
小智 38
我认为马特的答案是最好的,但我不相信这是对的.如果要替换换行符,则必须使用:
myString = Regex.Replace(myString, @"\s+", " ", RegexOptions.Multiline);
Run Code Online (Sandbox Code Playgroud)
cuo*_*gle 25
另一种使用LINQ的方法:
var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
str = string.Join(" ", list);
Run Code Online (Sandbox Code Playgroud)
Joe*_*orn 22
它比所有这些简单得多:
while(str.Contains(" ")) str = str.Replace(" ", " ");
Run Code Online (Sandbox Code Playgroud)
Scu*_*eve 21
即使只是简单的任务,正则表达式也会相当慢.这将创建一个可以在任何情况下使用的扩展方法string
.
public static class StringExtension
{
public static String ReduceWhitespace(this String value)
{
var newString = new StringBuilder();
bool previousIsWhitespace = false;
for (int i = 0; i < value.Length; i++)
{
if (Char.IsWhiteSpace(value[i]))
{
if (previousIsWhitespace)
{
continue;
}
previousIsWhitespace = true;
}
else
{
previousIsWhitespace = false;
}
newString.Append(value[i]);
}
return newString.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
它将被用作这样的:
string testValue = "This contains too much whitespace."
testValue = testValue.ReduceWhitespace();
// testValue = "This contains too much whitespace."
Run Code Online (Sandbox Code Playgroud)
Jan*_*rts 15
myString = Regex.Replace(myString, " {2,}", " ");
Run Code Online (Sandbox Code Playgroud)
Nol*_*nar 11
对于那些不喜欢的人Regex
,这里有一个方法使用StringBuilder
:
public static string FilterWhiteSpaces(string input)
{
if (input == null)
return string.Empty;
StringBuilder stringBuilder = new StringBuilder(input.Length);
for (int i = 0; i < input.Length; i++)
{
char c = input[i];
if (i == 0 || c != ' ' || (c == ' ' && input[i - 1] != ' '))
stringBuilder.Append(c);
}
return stringBuilder.ToString();
}
Run Code Online (Sandbox Code Playgroud)
在我的测试中,与静态编译的Regex相比,这种方法平均快16倍,中小型字符串非常大.与非编译或非静态正则表达式相比,这应该更快.
请记住,它并没有删除开头或结尾的空格,只有这样多次出现.
您只需在一个解决方案中执行此操作即可!
string s = "welcome to london";
s.Replace(" ", "()").Replace(")(", "").Replace("()", " ");
Run Code Online (Sandbox Code Playgroud)
如果您愿意,可以选择其他括号(甚至其他字符).
这是一个较短的版本,只有在你只执行一次时才会使用它,因为它Regex
每次调用时都会创建一个新的类实例.
temp = new Regex(" {2,}").Replace(temp, " ");
Run Code Online (Sandbox Code Playgroud)
如果你不熟悉正则表达式,这里有一个简短的解释:
在{2,}
使得用于它前面的字符正则表达式搜索,发现2和无限次之间的子串.
该.Replace(temp, " ")
内容替换字符串临时用空间中的所有比赛.
如果你想多次使用它,这是一个更好的选择,因为它在编译时创建了正则表达式IL:
Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
temp = singleSpacify.Replace(temp, " ");
Run Code Online (Sandbox Code Playgroud)
没有正则表达式,没有Linq ...删除前导和尾随空格以及将任何嵌入的多个空间段减少到一个空格
string myString = " 0 1 2 3 4 5 ";
myString = string.Join(" ", myString.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries));
Run Code Online (Sandbox Code Playgroud)
结果:"0 1 2 3 4 5"
根据乔尔的说法,合并其他答案,并希望随着我的进步而略有改善:
你可以这样做Regex.Replace()
:
string s = Regex.Replace (
" 1 2 4 5",
@"[ ]{2,}",
" "
);
Run Code Online (Sandbox Code Playgroud)
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 (" ");
Run Code Online (Sandbox Code Playgroud)
小智 5
// Mysample string
string str ="hi you are a demo";
//Split the words based on white sapce
var demo= str .Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
//Join the values back and add a single space in between
str = string.Join(" ", demo);
// output: string str ="hi you are a demo";
Run Code Online (Sandbox Code Playgroud)