【发布时间】:2009-10-29 18:07:00
【问题描述】:
如何在 VB.NET 中删除字符串中的空格?
【问题讨论】:
标签: vb.net
如何在 VB.NET 中删除字符串中的空格?
【问题讨论】:
标签: vb.net
删除所有空格:
myString = myString.Replace(" ", "")
删除前导和个尾随空格:
myString = myString.Trim()
注意:这会删除所有空格,因此会删除换行符、制表符等。
【讨论】:
String.Empty 可能是更现代的关键字。
2015:更新的 LINQ 和 lambda。
Function RemoveWhitespace(fullString As String) As String
Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function
这将删除字符串中的所有(空白)空格、前导、尾随和。
【讨论】:
原始帖子中的“空格”可能指的是空格,但还没有答案显示如何从字符串中删除所有 空格。因为正则表达式是我发现的最灵活的方法。
下面是一个控制台应用程序,您可以在其中看到仅替换空格或全部空格之间的区别。
您可以在 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
【讨论】:
修剪一个字符串,使其在一行中不包含两个或多个空格。 2 个或更多空间的每个实例将被修剪为 1 个空间。一个简单的解决方案:
While ImageText1.Contains(" ") '2 spaces.
ImageText1 = ImageText1.Replace(" ", " ") 'Replace with 1 space.
End While
【讨论】:
Regex.Replace 解决方案怎么样?
myStr = Regex.Replace(myStr, "\s", "")
【讨论】:
这将只删除空格,匹配 rtrim(ltrim(myString)) 的 SQL 功能
Dim charstotrim() As Char = {" "c}
myString = myString .Trim(charstotrim)
【讨论】:
您还可以使用一个小函数来循环并删除任何空格。
这是非常干净和简单的。
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
【讨论】:
Trim?只需使用接受的答案。
试试这个代码trimString
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
【讨论】: