删除字符串中多余的空格
我想使用 VB.net ex 删除多余的空格
。
"The Quick Brown Fox"
我想要输出
"The Quick Brown Fox"
谢谢, 英奇卡
I want to remove the excess white spaces using VB.net
ex.
"The Quick Brown Fox"
I want output
"The Quick Brown Fox"
Thanks,
inchika
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用一个简单的正则表达式来实现:
You can use a simple regular expression for that:
我意识到这个问题相当老了,但还有另一个选项不涉及正则表达式,或手动循环字符串并替换:
以及 C# 等效项:
使用“null”值作为
String.Split
原因分割字符是所有在发送到Char.IsWhiteSpace
。因此,以这种方式调用该方法将在所有空格上拆分字符串,删除空字符串,然后将其重新连接在一起,并在每个拆分数组元素之间添加一个空格。I realize that this question is fairly old, but there is another option that doesn't involve Regex, or manually looping through the string and replacing:
And the C# equivalent:
Using a "null" value as the split character on
String.Split
causes the split character to be all characters that return true if they were sent toChar.IsWhiteSpace
. Therefore, calling the method this way will split your string on all whitespace, remove the empty strings, then re-join it together with a single space in between each split array element.您真正想要的是将任何多个空格压缩为一个空格,一种方法是搜索两个空格并将它们替换为一个空格,直到没有两个相邻的空格为止,如下所示:
但是,这并不是万无一失的,因为 .net 字符串 的一些意识形态,这可能会发生进入无限循环,但仅限于一些非常奇怪的输入。
编辑:正如其他答案中所指出的,使用正则表达式这种特定的处理速度更快(也更简单)。
What you actually want is to compact any multiple white space to a single space, and one way to do that is to search for two spaces and replace them with a single space, until there are no two adjascent spaces left, something like this:
However, this is not fool-proof because of some ideosyncracies of .net strings, this might go into an endless loop, but only for some very odd inputs.
EDIT: This particular processing is faster (and simpler) using a regular expression, as pointed in the othe answers.
试试这个:
Try this: