Rocks
Rocks

Reputation: 127

Weird string manipulation issue

I am trying to make a series of strings exactly the same length. I am trying to do these steps :

  1. If the string is more than 25 characters, trim the extra.
  2. If it's less than 25, fill it up with spaces.
  3. Make sure that either way the strings are all 25 characters long.

Here is my code (or at least the relevant bit)

If Len(My.Settings.currOrder1) > 25 Then
    My.Settings.currOrder1 = Microsoft.VisualBasic.Left(My.Settings.currOrder1, 25)
Else
    My.Settings.currOrder1 = My.Settings.currOrder1 + "                           "
    My.Settings.currOrder1 = Microsoft.VisualBasic.Left(My.Settings.currOrder1, 25)
End If

which in my head should work. But if i run that code 3 times with a 6 character input, then 7, then 8, the output I get is this:

enter image description here

which is pretty obviously not shortening anything (the price is simply tacked on the end to show where the string ends). Any ideas?

Upvotes: 2

Views: 73

Answers (2)

Jaydip Jadhav
Jaydip Jadhav

Reputation: 12309

Try this :

Dim str As String = "Abc"
If str.Length < 25 Then
  str = str.PadRight(25 - str.Length, " "C)
Else
  str = str.Substring(0, 25)
End If

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460048

In general your VB6 approach should work also, but i'd use .NET:

Dim curOrder = My.Settings.currOrder1
If curOrder.Length > 25 Then
    My.Settings.currOrder1 = curOrder.Substring(0, 25)
ElseIf curOrder.Length < 25 Then
    My.Settings.currOrder1 = curOrder.PadRight(25, " "c)
End If
Debug.Assert( My.Settings.currOrder1.Length = 25 )

Upvotes: 0

Related Questions