简体   繁体   中英

Extract last 10 characters from a string of variable length in vb.net

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?

您需要使用Math.Min限制子字符串,以便它可以从字符串中获取10或尽可能多的子字符串。

mystring.Substring(mystring.Length - Math.Min(10, mystring.Length))

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.

你可以反转字符串(将其转换为字符数组),从start开始取10个字符,然后将其反转并通过连接数组转换为字符串。

String.Join("", mystring.Reverse().Take(10).Reverse())
Microsoft.VisualBasic.Strings.Right(mystring, 10)

Another simple but efficient solution i found :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM