简体   繁体   English

从vb.net中的可变长度字符串中提取最后10个字符

[英]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 现在我想提取最后10个字符并得到这个结果

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? 上面的代码适用于长度大于9的字符串,但是great如何使用最少的vb.net代码来克服这个问题?

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

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

The Strings.Right Method will do what you want. Strings.Right方法将做你想要的。

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)) mystring.Substring(Math.Max(0,mystring.Length - 10))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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