3

I have some sentences like below :

i have a river  
he is liar
great
hello miss
there was a river in this area

Now i want to extract last 10 characters and have this result

ve a river
he is liar
great
hello miss
 this area

I have tried to achieve the desired result using this

mystring.Substring(mystring.Length - 10)

The above code works fine for the strings of length higher than 9, but fails for great How to overcome this problem using fewest line of vb.net code?

Md. Suman Kabir
  • 5,243
  • 5
  • 25
  • 43

4 Answers4

4

You need to cap the substring using Math.Min so that it will grab 10 or as many as it can from the string.

mystring.Substring(mystring.Length - Math.Min(10, mystring.Length))
Mike Parkhill
  • 5,511
  • 1
  • 28
  • 38
3

The Strings.Right Method will do what you want.

Dim ss = {"i have a river", "he is liar", "great", "hello miss", "there was a river in this area"}
For Each s In ss
    Console.WriteLine(Strings.Right(s, 10))
Next

Outputs:

ve a river
he is liar
great
hello miss
 this area

I assume that the missing space at the start of the last string was a transcription error in the question.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
1

You can reverse the string (which converts it to array of character), take 10 characters from start, then reverse it back and convert to string by joining array.

String.Join("", mystring.Reverse().Take(10).Reverse())
Misaz
  • 3,694
  • 2
  • 26
  • 42
1
Microsoft.VisualBasic.Strings.Right(mystring, 10)

Another simple but efficient solution i found :

mystring.Substring(Math.Max(0, mystring.Length - 10))

Md. Suman Kabir
  • 5,243
  • 5
  • 25
  • 43