从VB.NET中的string中删除空格

如何从VB.NET中的string中删除空格?

2015年:更新的LINQ&lambda。

  1. 由于这是一个老Q(和答案),只是想用新的2015年方法更新它。
  2. 原始的“空格”可以引用非空格的空格(即制表符,换行符,段落分隔符,换行符,回车符等等)。
  3. 此外,Trim()只从string的前面/后面删除空格,它不会删除string中的空格; 例如:“领导和尾随空间”将成为“领导和尾随空间”,但里面的空间仍然存在。

Function RemoveWhitespace(fullString As String) As String Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray()) End Function 

这将删除所有(白色) – 空格,前导,尾随和string内。

删除所有空间:

  myString = myString.Replace(" ", "") 

删除前后空格:

 myString = myString.Trim() 

注意:这将删除任何空格,所以换行符,制表符等将被删除。

修剪一个string,使其不包含两个或更多空格在一行中。 2个或更多空间的每个实例将被修剪到1个空间。 简单的解决scheme:

 While ImageText1.Contains(" ") '2 spaces. ImageText1 = ImageText1.Replace(" ", " ") 'Replace with 1 space. End While 

原始文章中的“空格”可能引用空格,但没有答案显示如何从string中删除所有空格 。 对于这个正则expression式来说是我find的最灵活的方法。

下面是一个控制台应用程序,您可以看到replace空格或全部空格之间的区别。

您可以在http://msdn.microsoft.com/en-us/library/hs600312.aspx和http://msdn.microsoft.com/en-us/library/az24scfc.aspx上find有关;.NET正则expression式的更多信息

 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 

你也可以使用一个小函数来循环并移除任何空格。

这是非常干净和简单。

 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 

这将只删除空格,匹配rtrim(ltrim(myString))的SQLfunction

 Dim charstotrim() As Char = {" "c} myString = myString .Trim(charstotrim) 

Regex.Replace解决scheme呢?

 myStr = Regex.Replace(myStr, "\s", "") 

试试这个代码来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