34

I want to get the last 5 digits/characters from a string. For example, from "I will be going to school in 2011!", I would like to get "2011!".

Any ideas? I know Visual Basic has Right(string, 5); this didn't work for me and gave me an error.

Ry-
  • 218,210
  • 55
  • 464
  • 476
NULL
  • 1,559
  • 5
  • 34
  • 60

7 Answers7

71
str.Substring(str.Length - 5)
dcp
  • 54,410
  • 22
  • 144
  • 164
29

Error check:

result = str.Substring(Math.Max(0, str.Length - 5))
Glennular
  • 17,827
  • 9
  • 58
  • 77
6

Checks for errors:

Dim result As String = str
If str.Length > 5 Then
    result = str.Substring(str.Length - 5)
End If
Nick Gotch
  • 9,167
  • 14
  • 70
  • 97
4

Old thread, but just only to say: to use the classic Left(), Right(), Mid() right now you don't need to write the full path (Microsoft.VisualBasic.Strings). You can use fast and easily like this:

Strings.Right(yourString, 5)
iminiki
  • 2,549
  • 12
  • 35
  • 45
Toni
  • 41
  • 2
3

in VB 2008 (VB 9.0) and later, prefix Right() as Microsoft.VisualBasic.Right(string, number of characters)

Dim str as String = "Hello World"

Msgbox(Microsoft.VisualBasic.Right(str,5))

'World"

Same goes for Left() too.

StackOverflowUser
  • 945
  • 12
  • 10
Umesh Vora
  • 39
  • 1
2

The accepted answer of this post will cause error in the case when the string length is lest than 5. So i have a better solution. We can use this simple code :

If(str.Length <= 5, str, str.Substring(str.Length - 5))

You can test it with variable length string.

    Dim str, result As String
    str = "11!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)
    str = "I will be going to school in 2011!"
    result = If(str.Length <= 5, str, str.Substring(str.Length - 5))
    MessageBox.Show(result)

Another simple but efficient solution i found :

str.Substring(str.Length - Math.Min(5, str.Length))

Md. Suman Kabir
  • 5,243
  • 5
  • 25
  • 43
0
Dim a As String = Microsoft.VisualBasic.right("I will be going to school in 2011!", 5)
MsgBox("the value is:" & a)
Md. Suman Kabir
  • 5,243
  • 5
  • 25
  • 43
dinesh
  • 1