C# 从字符串中仅提取最右边的 n 个字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1722334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:15:07  来源:igfitidea点击:

Extract only right most n letters from a string

c#stringsubstring

提问by Shyju

How can I extract a substringwhich is composed of the rightmost six letters from another string?

如何substring从另一个中提取由最右边的六个字母组成的a string

Ex: my string is "PER 343573". Now I want to extract only "343573".

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

How can I do this?

我怎样才能做到这一点?

采纳答案by Vilx-

string SubString = MyString.Substring(MyString.Length-6);

回答by cjk

Use this:

用这个:

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

回答by James

Probably nicer to use an extension method:

使用扩展方法可能更好:

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

Usage

用法

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

回答by RvdK

MSDN

MSDN

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

EDIT: too slow...

编辑:太慢了...

回答by stevehipwell

Write an extension method to express the Right(n);function. The function should deal with null or empty strings returning an empty string, strings shorter than the max length returning the original string and strings longer than the max length returning the max length of rightmost characters.

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

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;
}

回答by chills42

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;

回答by Wade

Guessing at your requirements but the following regular expression will yield only on 6 alphanumerics before the end of the string and no match otherwise.

猜测您的要求,但以下正则表达式只会产生字符串末尾之前的 6 个字母数字,否则不会匹配。

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

回答by Wade

Without resorting to the bit converter and bit shifting (need to be sure of encoding) this is fastest method I use as an extension method '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);
}

回答by Mahdi Tahsildari

if you are not sure of the length of your string, but you are sure of the words count (always 2 words in this case, like 'xxx yyyyyy') you'd better use split.

如果您不确定字符串的长度,但您确定字数(在这种情况下始终为 2 个字,例如 'xxx yyyyyy'),则最好使用 split。

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

this always returns the second word of your string.

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

回答by Jeff Crawford

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
}

Shouldn't error, returns nulls as empty string, returns trimmed or base values. Use it like "testx".Left(4) or str.Right(12);

不应该出错,返回空字符串作为空字符串,返回修剪或基值。像 "testx".Left(4) 或 str.Right(12) 一样使用它;