Results 1 to 4 of 4

Thread: Formatting a string: truncating or padding

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    2,012

    Formatting a string: truncating or padding

    I need to take a string of any length & make it exactly 5 characters long by either truncating it or padding it or neither.
    So "abcdefgh" becomes "abcde", "abcde" stays "abcde" & "abc" becomes "abc " (2 spaces at the end).

    I currently use this line of code:

    Code:
    Microsoft.VisualBasic.Left(myString, 5).PadRight(5, " "c)
    it works, but it seems very hackish. Can anyone see a more elegant way? Thanks...

  2. #2
    Frenzied Member
    Join Date
    Sep 2006
    Location
    Scotland
    Posts
    1,054

    Re: Formatting a string: truncating or padding

    I would use var.PadRight(5).Substring(0, 5) but other than that I can't see any issues?

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

    Re: Formatting a string: truncating or padding

    i can't improve it other than using uptodate .net methods:

    vb Code:
    1. MsgBox(myString.Substring(0, Math.Min(myString.Length, 5)).PadRight(5, " "c) & "|") 'added | for a visual cue

  4. #4
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Formatting a string: truncating or padding

    Code:
            Dim foo() As String = New String() {"abcdefgh", "edcba", "xyz"} 'strings to test
    
            For Each s As String In foo
                Dim sb As New System.Text.StringBuilder(s)
                sb.Append("     ")
                sb.Length = 5
                Debug.WriteLine(sb.ToString)
    
                'or
                's = s.PadRight(5, " "c).Substring(0, 5) 
                s = s.PadRight(5, "*"c).Substring(0, 5) 'test
                Debug.WriteLine(s)
                Debug.WriteLine("")
            Next
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

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