只从字符串中提取最右边的 n 个字母

我怎样才能从另一个 string中提取一个由最右边的六个字母组成的 substring呢?

例句: 我的字符串是 "PER 343573"。现在我只想提取 "343573"

我怎么能这么做?

308827 次浏览
string SubString = MyString.Substring(MyString.Length-6);

用这个:

String text = "PER 343573";
String numbers = text;
if (text.Length > 6)
{
numbers = text.Substring(text.Length - 6);
}

使用扩展方法可能更好:

public static class StringExtensions
{
public static string Right(this string str, int length)
{
return str.Substring(str.Length - length, length);
}
}

用法

string myStr = "PER 343573";
string subStr = myStr.Right(6);

MSDN

String mystr = "PER 343573";
String number = mystr.Substring(mystr.Length-6);

编辑: 太慢了..。

编写一个扩展方法来表示 Right(n);函数。函数应该处理返回空字符串的 null 或空字符串,返回原字符串的字符串短于最大长度,返回最右边字符的最大长度的字符串长于最大长度。

public static string Right(this string sValue, int iMaxLength)
{
//Check if the value is valid
if (string.IsNullOrEmpty(sValue))
{
//Set valid empty string as string could be null
sValue = string.Empty;
}
else if (sValue.Length > iMaxLength)
{
//Make the string no longer than the max length
sValue = sValue.Substring(sValue.Length - iMaxLength, iMaxLength);
}


//Return the string
return sValue;
}

This isn't exactly what you are asking for, but just looking at the example, it appears that you are looking for the numeric section of the string.

If this is always the case, then a good way to do it would be using a regular expression.

var regex= new Regex("\n+");
string numberString = regex.Match(page).Value;

猜测您的需求,但是下面的正则表达式只会在字符串结尾之前的6个字母数字中产生,否则不会匹配。

string result = Regex.Match("PER 343573", @"[a-zA-Z\d]{6}$").Value;

无需借助位转换器和位移(需要确保编码) 这是我用作扩展方法‘ Right’的最快的方法。

string myString = "123456789123456789";


if (myString > 6)
{


char[] cString = myString.ToCharArray();
Array.Reverse(myString);
Array.Resize(ref myString, 6);
Array.Reverse(myString);
string val = new string(myString);
}

如果您不确定字符串的长度,但确定单词计数(在这种情况下总是2个单词,比如‘ xxx yyyyyy’) ,那么最好使用 split。

string Result = "PER 343573".Split(" ")[1];

它总是返回字符串的第二个单词。

using System;


public static class DataTypeExtensions
{
#region Methods


public static string Left(this string str, int length)
{
str = (str ?? string.Empty);
return str.Substring(0, Math.Min(length, str.Length));
}


public static string Right(this string str, int length)
{
str = (str ?? string.Empty);
return (str.Length >= length)
? str.Substring(str.Length - length, length)
: str;
}


#endregion
}

如果不出错,返回空值作为空字符串,返回修剪后的值或基值

这是我用的解决办法。 它检查输入字符串的长度不小于请求的长度。不幸的是,我在上面看到的解决方案没有考虑到这一点——这可能会导致崩溃。

    /// <summary>
/// Gets the last x-<paramref name="amount"/> of characters from the given string.
/// If the given string's length is smaller than the requested <see cref="amount"/> the full string is returned.
/// If the given <paramref name="amount"/> is negative, an empty string will be returned.
/// </summary>
/// <param name="string">The string from which to extract the last x-<paramref name="amount"/> of characters.</param>
/// <param name="amount">The amount of characters to return.</param>
/// <returns>The last x-<paramref name="amount"/> of characters from the given string.</returns>
public static string GetLast(this string @string, int amount)
{
if (@string == null) {
return @string;
}


if (amount < 0) {
return String.Empty;
}


if (amount >= @string.Length) {
return @string;
} else {
return @string.Substring(@string.Length - amount);
}
}

用这个:

String mystr = “ PER 343573”; Int number = Convert.ToInt32(mystr.Replace (“ PER”,“”)) ;

因为您使用的是. NET,它们都编译成 MSIL,所以只需引用 微软,VisualBasic使用微软内置的 Strings.Right方法:

using Microsoft.VisualBasic;
...
string input = "PER 343573";
string output = Strings.Right(input, 6);

不需要创建自定义扩展方法或其他工作。结果是通过一个引用和一行简单的代码实现的。

As further info on this, using Visual Basic methods with C# has been documented elsewhere. I personally stumbled on it first when trying to parse a file, and found 这个线索 on using the Microsoft.VisualBasic.FileIO.TextFieldParser class to be extremely useful for parsing .csv files.

I use the Min to prevent the negative situations and also handle null strings

// <summary>
/// Returns a string containing a specified number of characters from the right side of a string.
/// </summary>
public static string Right(this string value, int length)
{
string result = value;
if (value != null)
result = value.Substring(0, Math.Min(value.Length, length));
return result;
}

这是我使用的方法: 我喜欢让事情简单。

private string TakeLast(string input, int num)
{
if (num > input.Length)
{
num = input.Length;
}
return input.Substring(input.Length - num);
}
using Microsoft.visualBasic;


public class test{
public void main(){
string randomString = "Random Word";
print (Strings.right(randomString,4));
}
}

输出为“ Word”

Another solution that may not be mentioned

S.Substring(S.Length < 6 ? 0 : S.Length - 6)

无效安全方法:

返回原始字符串的字符串短于最大长度

字符串右扩展方法

public static string Right(this string input, int count) =>
String.Join("", (input + "").ToCharArray().Reverse().Take(count).Reverse());

String Left Extension Method

public static string Left(this string input, int count) =>
String.Join("", (input + "").ToCharArray().Take(count));

只是一个想法:

public static string Right(this string @this, int length) {
return @this.Substring(Math.Max(@this.Length - length, 0));
}
//s - your string
//n - maximum number of right characters to take at the end of string
(new Regex("^.*?(.{1,n})$")).Replace(s,"$1")
var str = "PER 343573";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty
: str.Length < 6 ? str
: str.Substring(str.Length - 6); // "343573"
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // "343573"

这支持 str中的任意数量的字符。可选代码不支持 null字符串。而且,第一个更快,第二个更紧凑。

如果知道包含短字符串的 str,我更喜欢第二个。如果是长线的话,第一根比较合适。

例如:。

var str = "";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty
: str.Length < 6 ? str
: str.Substring(str.Length - 6); // ""
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // ""

或者

var str = "123";
var right6 = string.IsNullOrWhiteSpace(str) ? string.Empty
: str.Length < 6 ? str
: str.Substring(str.Length - 6); // "123"
// alternative
var alt_right6 = new string(str.Reverse().Take(6).Reverse().ToArray()); // "123"
            //Last word of string :: -> sentence
var str  ="A random sentence";
var lword = str.Substring(str.LastIndexOf(' ') + 1);


//Last 6 chars of string :: -> ntence
var n = 6;
var right = str.Length >n ? str.Substring(str.Length - n) : "";