Dav*_*vid 76
要删除所有空格:
myString = myString.Replace(" ", "")
Run Code Online (Sandbox Code Playgroud)
要删除前导和尾随空格:
myString = myString.Trim()
Run Code Online (Sandbox Code Playgroud)
注意:这将删除任何空格,因此将删除换行符,制表符等.
Jos*_*Lee 20
2015年:更新的LINQ&lambda.
Function RemoveWhitespace(fullString As String) As String
Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function
Run Code Online (Sandbox Code Playgroud)
这将删除字符串中的所有(白色)空格,前导,尾随和.
Jas*_*n S 15
原始帖子中的"空格"可以引用空白,但没有答案显示如何从字符串中删除所有空格.因为正则表达式是我发现的最灵活的方法.
下面是一个控制台应用程序,您可以在其中看到替换空格或所有空格之间的区别.
您可以在http://msdn.microsoft.com/en-us/library/hs600312.aspx和http://msdn.microsoft.com/en-us/library/az24scfc.aspx上找到有关.NET正则表达式的更多信息.
Imports System.Text.RegularExpressions
Module TestRegExp
Sub Main()
' Use to match all whitespace (note the lowercase s matters)
Dim regWhitespace As New Regex("\s")
' Use to match space characters only
Dim regSpace As New Regex(" ")
Dim testString As String = "First Line" + vbCrLf + _
"Second line followed by 2 tabs" + vbTab + vbTab + _
"End of tabs"
Console.WriteLine("Test string :")
Console.WriteLine(testString)
Console.WriteLine("Replace all whitespace :")
' This prints the string on one line with no spacing at all
Console.WriteLine(regWhitespace.Replace(testString, String.Empty))
Console.WriteLine("Replace all spaces :")
' This removes spaces, but retains the tabs and new lines
Console.WriteLine(regSpace.Replace(testString, String.Empty))
Console.WriteLine("Press any key to finish")
Console.ReadKey()
End Sub
End Module
Run Code Online (Sandbox Code Playgroud)
小智 14
要向下修剪字符串,使其不包含一行中的两个或多个空格.每个2个或更多空间的实例将被裁减为1个空格.简单的解决方案:
While ImageText1.Contains(" ") '2 spaces.
ImageText1 = ImageText1.Replace(" ", " ") 'Replace with 1 space.
End While
Run Code Online (Sandbox Code Playgroud)
Regex.Replace 解决方案怎么样?
myStr = Regex.Replace(myStr, "\s", "")
Run Code Online (Sandbox Code Playgroud)