Get last 5 characters in a string

前端 未结 8 1587
青春惊慌失措
青春惊慌失措 2020-12-09 15:14

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!\".<

相关标签:
8条回答
  • 2020-12-09 15:54

    I opened this thread looking for a quick solution to a simple question, but I found that the answers here were either not helpful or overly complicated. The best way to get the last 5 chars of a string is, in fact, to use the Right() method. Here is a simple example:

    Dim sMyString, sLast5 As String
    
    sMyString = "I will be going to school in 2011!"
    sLast5 = Right(sMyString, - 5)
    MsgBox("sLast5 = " & sLast5)
    

    If you're getting an error then there is probably something wrong with your syntax. Also, with the Right() method you don't need to worry much about going over or under the string length. In my example you could type in 10000 instead of 5 and it would just MsgBox the whole string, or if sMyString was NULL or "", the message box would just pop up with nothing.

    0 讨论(0)
  • 2020-12-09 15:56
    str.Substring(str.Length - 5)
    
    0 讨论(0)
  • 2020-12-09 15:59

    Error check:

    result = str.Substring(Math.Max(0, str.Length - 5))
    
    0 讨论(0)
  • 2020-12-09 16:00

    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.

    0 讨论(0)
  • 2020-12-09 16:02
    Dim a As String = Microsoft.VisualBasic.right("I will be going to school in 2011!", 5)
    MsgBox("the value is:" & a)
    
    0 讨论(0)
  • 2020-12-09 16:05

    Checks for errors:

    Dim result As String = str
    If str.Length > 5 Then
        result = str.Substring(str.Length - 5)
    End If
    
    0 讨论(0)
提交回复
热议问题