Results 1 to 2 of 2

Thread: [RESOLVED] Remove All Whitespace

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,005

    Resolved [RESOLVED] Remove All Whitespace

    I am wanting to remove all whitespace from a String. I know that I can use LINQ or RegEx:
    Code:
    'LINQ
    Dim input As String = New String(Console.ReadLine().Where(Function(c) Not Char.IsWhitespace(c)).ToArray())
    
    'RegEx
    Dim input As String = New Regex("\s+").Replace(Console.ReadLine, String.Empty)
    However, I find it odd that I cannot do the same thing using only the System namespace without having to loop through the String. For example, I've tried this:
    Code:
    'Replace
    Dim input As String = Console.ReadLine().Replace(" ", String.Empty)
    However, this will not remove whitespace like double spaces. So then I tried:
    Code:
    'Concat/Split
    Dim input As String = String.Concat(Console.ReadLine().Split({" "c}, StringSplitOptions.RemoveEmptyEntries))
    But this also doesn't account for whitespace like double spaces. Ultimately the only thing that I could get to work is:
    Code:
    'For/Next Loop
    Dim input As String = Console.ReadLine()
    For x As Integer = input.Length - 1 To 0 Step -1
        If Char.IsWhiteSpace(input(x)) Then
            input = input.Remove(x, 1)
        End If
    Next
    So my question to you is there any 1 liners that could do the same thing that the LINQ, RegEx, or For/Next loop examples do?
    "Code is like humor. When you have to explain it, itís bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  2. #2

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,005

    Re: Remove All Whitespace

    Found the solution here: http://stackoverflow.com/a/25288858

    Code:
    Dim input As String = String.Concat(Console.ReadLine().Split(New Char() {}, StringSplitOptions.RemoveEmptyEntries))
    "Code is like humor. When you have to explain it, itís bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width