vb.net 将多个空格替换为一个?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20977246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing multiple spaces into just one?
提问by bloodless2010
Okay, so I am working on this VB.NET program and I have tried using the .replace() to do this but it's not the best way to do this. I have a string with multiple spaces in between data which I don't want, what would be the best way to strip the spaces from the string but 1?
好的,所以我正在研究这个 VB.NET 程序,我尝试使用 .replace() 来做到这一点,但这不是做到这一点的最佳方法。我有一个字符串,在我不想要的数据之间有多个空格,从字符串中去除空格但 1 的最佳方法是什么?
回答by Guffa
Use a regular expression to match multiple spaces and replace with a single space:
使用正则表达式匹配多个空格并替换为单个空格:
s = Regex.Replace(s, " {2,}", " ")
回答by Charlie Kilian
Here's a way using arrays, in case you'd prefer to avoid regular expressions.
这是一种使用数组的方法,以防您希望避免使用正则表达式。
Given this starting string:
鉴于此起始字符串:
Dim str As String = "This is a test string"
You can do this:
你可以这样做:
Dim arr As String() = str.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
Dim compressedSpaces As String = String.Join(" ", arr)
You can also combine it onto one line:
您也可以将其合并为一行:
Dim newString As String = String.Join(" ", str.Split({" "c},
StringSplitOptions.RemoveEmptyEntries))

