Results 1 to 4 of 4

Thread: [RESOLVED] Instead of one charcter it outputs three spaces

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Oct 2013
    Posts
    200

    Resolved [RESOLVED] Instead of one charcter it outputs three spaces

    Hello, I'm trying to remove last spaces from some strings however my function behaves strangely.

    For example when my string is: "word1 word2 word3 word4 "

    ... and function is
    Code:
    Private Function TrimLastSpaces(s As String) As String
    
            Dim i As Integer
            For i = s.Length To 0 Step -1
    
                If (Mid(s, i - 2, i - 1) = " ") Then
                    Console.WriteLine("s = " & s)
                    s = Mid(s, 1, s.Length - 2)
                    i = s.Length()
                Else
                    Console.WriteLine(Mid(s, i - 2, i - 1))
                    Exit For
                End If
            Next
    
            Return s
    
        End Function
    it doesn't go in "if" statement, it goes in "else" statement and outputs three space charcters while I'm expecting it to remove space characters one by one.

    Maybe it's a very simple thing I'm missing but I couldn't figure it out.

  2. #2

    Thread Starter
    Addicted Member
    Join Date
    Oct 2013
    Posts
    200

    Re: Instead of one charcter it outputs three spaces

    Ok, I missed it again. I think it should be: If (Mid(s, i - 1, 1) = " ") Then
    Last edited by nikel; Mar 29th, 2015 at 10:22 AM.

  3. #3
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    23,394

    Re: Instead of one charcter it outputs three spaces

    try this:

    Code:
    Private Function TrimLastSpaces(ByVal s As String) As String
        Return String.Concat(s.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries))
    End Function

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Oct 2013
    Posts
    200

    Re: [RESOLVED] Instead of one charcter it outputs three spaces

    Thank you for your reply. The code you gave didn't change the string.

    Edit: I forgot "str = TrimLastSpaces(str)" and tried it again but it removed all spaces instead of the last ones.
    Last edited by nikel; Mar 29th, 2015 at 11:09 AM.

Tags for this Thread

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