Get last 5 characters in a string

前端 未结 8 1588
青春惊慌失措
青春惊慌失措 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 16:06

    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))

    0 讨论(0)
  • 2020-12-09 16:06

    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)
    
    0 讨论(0)
提交回复
热议问题