Mega Code Archive

 
Categories / VB.Net Tutorial / Data Type
 

Remove white space in a string

Public Class Tester     Public Shared Sub Main         Dim source As String = _             Space(17) & "This    string    had " & Chr(12) & _             StrDup(5, Chr(9)) & "extra whitespace. " & Space(27)         Dim thisIsWhiteSpace As Boolean         Dim prevIsWhiteSpace As Boolean         Dim result As New System.Text.StringBuilder(source.Length)         Dim counter As Integer         For counter = 0 To source.Length - 1             prevIsWhiteSpace = thisIsWhiteSpace             thisIsWhiteSpace = Char.IsWhiteSpace(source.Chars(counter))             If (thisIsWhiteSpace = False) Then                 If (prevIsWhiteSpace = True) AndAlso _                    (result.Length > 0) Then result.Append(Space(1))                 result.Append(source.Chars(counter))             End If         Next counter         Console.WriteLine(result.ToString())     End Sub End Class This string had extra whitespace.