如何从VB.NET中的字符串中删除空格?
答案 0 :(得分:73)
删除所有空格:
myString = myString.Replace(" ", "")
删除前导和尾随空格:
myString = myString.Trim()
注意:这会删除任何空白区域,因此会删除换行符,标签页等。
答案 1 :(得分:19)
2015:更新的LINQ&拉姆达。
// In the case of CACHE_THEN_NETWORK, two callbacks will be called. We can only remove the
// query after the second callback.
if (Parse.isLocalDatastoreEnabled() || query.getCachePolicy() != CachePolicy.CACHE_THEN_NETWORK ||
(query.getCachePolicy() == CachePolicy.CACHE_THEN_NETWORK && !firstCallBack.get())) {
runningQueries.remove(query);
}
这将删除所有(白色)空格,前导,尾随和字符串。
答案 2 :(得分:14)
原始帖子中的“空格”可以引用空格,但还没有答案显示如何从字符串中删除所有空格。因为正则表达式是我发现的最灵活的方法。
下面是一个控制台应用程序,您可以在其中看到替换空格或所有空格之间的区别。
您可以在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
答案 3 :(得分:13)
要剪裁字符串,使其不包含一行中的两个或多个空格。每个2个或更多空间的实例将被裁减为1个空格。一个简单的解决方案:
While ImageText1.Contains(" ") '2 spaces.
ImageText1 = ImageText1.Replace(" ", " ") 'Replace with 1 space.
End While
答案 4 :(得分:3)
这将仅删除空格,匹配rtrim的SQL功能(ltrim(myString))
Dim charstotrim() As Char = {" "c}
myString = myString .Trim(charstotrim)
答案 5 :(得分:3)
Regex.Replace解决方案怎么样?
myStr = Regex.Replace(myStr, "\s", "")
答案 6 :(得分:2)
您还可以使用一个小的函数来循环并删除任何空格。
这非常简洁。
Public Shared Function RemoveXtraSpaces(strVal As String) As String
Dim iCount As Integer = 1
Dim sTempstrVal As String
sTempstrVal = ""
For iCount = 1 To Len(strVal)
sTempstrVal = sTempstrVal + Mid(strVal, iCount, 1).Trim
Next
RemoveXtraSpaces = sTempstrVal
Return RemoveXtraSpaces
End Function
答案 7 :(得分:0)
请尝试使用此代码转至trim
String
Public Function AllTrim(ByVal GeVar As String) As String
Dim i As Integer
Dim e As Integer
Dim NewStr As String = ""
e = Len(GeVar)
For i = 1 To e
If Mid(GeVar, i, 1) <> " " Then
NewStr = NewStr + Mid(GeVar, i, 1)
End If
Next i
AllTrim = NewStr
' MsgBox("alltrim = " & NewStr)
End Function