Cheddar
Cheddar

Reputation: 530

Pulling a specific number from a string of numbers in vb.net

I am currently working in vb.net express 2013. I am using windows form applications. I need to pull the third from last number in a string of numbers without getting the other numbers behind it. I found this question on this website, Get last 5 characters in a string, which is very close to what I need. However, this code pulls ALL of the last 5 characters, and in my code, I need the third to last without any other numbers. For example, if you take the number "917408," I need to select the "4." With this I am going to create an IF statement based on what number is returned from the original long number.

      'Ghost Floor
    If CBJob1.Visible Then
        If Shear1.Text >= 3 Then
            Dim ghostshear1 As String = Shear1.Text
            Dim len = ghostshear1.Length
            Dim result = ghostshear1.Substring(len - 3, 1)
            MsgBox(result)
        End If
    End If

Upvotes: 2

Views: 2751

Answers (3)

SnookerC
SnookerC

Reputation: 170

As Robert Harvey pointed out in the comments above, you just need to alter your Substring arguments:

EDIT: based on @OP's comments about the string changing between 6 and 7 characters:

    Dim strValue As String = "917408"
    Dim newValue As String

    newValue = strValue.PadLeft(7, "0").Substring(4, 1)
    MessageBox.Show(newValue)

Upvotes: 2

Jason Down
Jason Down

Reputation: 22171

Another approach is to convert the string to an integer and then grab the 100s column (third last column in any digit >= 100).

Dim strValue As String = "917408"
Dim number As Int32 = Convert.ToInt32(strValue)
Dim hundredsDigit As Int32
hundredsDigit = (number / 100) Mod 10

If your number is already an actual number (and not a string) this will save you from having to convert it to a string to begin with.

Upvotes: 4

Steve
Steve

Reputation: 216293

To extract a character in a particular position counting from the end of the string you need to know the length of the string. This is really easy.

Dim test = "917408"
if test.Length >= 3 then
    Dim len = test.Length
    Dim result = test.Substring(len - 3, 1)
End if

Now, you need the 3rd character from the end, so you should add a check to avoid referencing a negative position in case the string is less than 3 characters

The key to your solution is the string class Substring method that takes two parameters:

  • a starting point (len - 3)
  • the number of characters to return (in your case 1)

Upvotes: 3

Related Questions