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

Shy*_*yju 105 c# string substring

如何从另一个字符串中提取由最右边六个字母组成的子字符串?

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

我怎样才能做到这一点?

Vil*_*lx- 150

string SubString = MyString.Substring(MyString.Length-6);
Run Code Online (Sandbox Code Playgroud)

  • 如果字符串不是所需的字符数,则此aproach无法正常工作. (34认同)
  • @James--和pernickity一样,只有标题提到"n个字母".提出的实际问题是"最右边的六个字母":) (3认同)
  • @JohannesRössel - 我是正则表达式的忠实粉丝(请参阅我的答案),但我不会因为像这样的简单情况而推荐它们.使用函数包装器的任何答案都比正则表达式更适合编码维护.扩展方法(或标准函数,如果.NET 2.0)是最佳解决方案. (2认同)

ste*_*ell 68

编写扩展方法来表达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;
}
Run Code Online (Sandbox Code Playgroud)

  • @Jalle,VB.NET有Left,Right和Mid作为顶级函数,以及许多其他不属于C#的有用的东西.不知道为什么,因为其中许多都是不错的功能. (4认同)
  • 很好的答案,但在C#代码中看到匈牙利符号有点过分. (3认同)
  • @James - 在调用子字符串之前,它不会像`sValue.Length> iMaxLength`一样! (2认同)

Jam*_*mes 38

可能更好使用扩展方法:

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

用法

string myStr = "ABCDEPER 343573";
string subStr = myStr.Right(6);
Run Code Online (Sandbox Code Playgroud)

  • 然后它会抛出一个NullReferenceException,就像你尝试在空字符串上使用任何方法一样... (19认同)
  • `str.Length - length` 可以为负数。第二个参数也是可选的。无需传递长度。 (2认同)

Jef*_*ord 26

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
}
Run Code Online (Sandbox Code Playgroud)

不应该出错,将nulls作为空字符串返回,返回trimmed或base值.使用它像"testx".Left(4)或str.Right(12);


Rvd*_*vdK 13

MSDN

String mystr = "PER 343573";
String number = mystr.Substring(mystr.Length-6);
Run Code Online (Sandbox Code Playgroud)

编辑:太慢了......


Mah*_*ari 9

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

string Result = "PER 343573".Split(" ")[1];
Run Code Online (Sandbox Code Playgroud)

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


chi*_*s42 7

这不完全是你要求的,但只是看一下这个例子,看来你正在寻找字符串的数字部分.

如果总是这样,那么一个好方法就是使用正则表达式.

var regex= new Regex("\n+");
string numberString = regex.Match(page).Value;
Run Code Online (Sandbox Code Playgroud)

  • 旧答案,但 +1 支持使用正则表达式。特别是因为 .NET 的 String 实现中(仍然)没有内置方法来执行此操作@James。不然这个问题可能根本不存在。 (2认同)

cjk*_*cjk 5

用这个:

String text = "PER 343573";
String numbers = text;
if (text.Length > 6)
{
    numbers = text.Substring(text.Length - 6);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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

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


Aar*_*mas 5

由于您使用的都是.NET(都可编译为MSIL),因此只需引用Microsoft.VisualBasic,然后使用Microsoft的内置Strings.Right方法

using Microsoft.VisualBasic;
...
string input = "PER 343573";
string output = Strings.Right(input, 6);
Run Code Online (Sandbox Code Playgroud)

无需创建自定义扩展方法或其他工作。使用一个参考和一个简单的代码行即可获得结果。

作为对此的更多信息,其他地方已记录了将Visual Basic方法与C#结合使用的情况。我个人无意中发现它试图解析文件时先,发现该SO线程使用的Microsoft.VisualBasic.FileIO.TextFieldParser类是分析的.csv文件非常有用。


Sup*_*nno 5

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"
Run Code Online (Sandbox Code Playgroud)

这支持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()); // ""
Run Code Online (Sandbox Code Playgroud)

或者

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"
Run Code Online (Sandbox Code Playgroud)