假设我有一个字符串:

"34234234d124"

我想要得到这个字符串的最后四个字符,这个字符串是“d124”。我可以使用SubString,但它需要几行代码,包括命名一个变量。

是否有可能在c#的一个表达式中得到这个结果?


当前回答

你所要做的就是…

String result = mystring.Substring(mystring.Length - 4);

其他回答

这不仅仅是一个OP问题,而是一个如何将字符串的后3用于特定目的的例子。在我的例子中,我想对存储为字符串(1到3位数字)的数字字段进行数值排序(LINQ OrderBy)。所以,为了让字符串数字像数字一样排序,我需要用零填充字符串数字,然后取最后3。结果orderderby语句是:

myList = myList.OrderBy(x => string.Concat("00",x.Id)[^3..])

OrderBy语句中使用的string.Concat()会生成像“001”,“002”,“011”,“021”,“114”这样的字符串,如果它们被存储为数字,它们就会按照它们的方式排序。

我将从不同来源修改的一些代码放在一起,可以得到您想要的结果,并且还可以做更多的事情。我已经允许负int值,int值超过字符串长度,并且结束索引小于开始索引。在最后一种情况下,该方法返回一个倒序子字符串。有很多评论,但如果有什么不清楚或疯狂的地方请告诉我。我一直在摆弄这个,想看看能用它做什么。

    /// <summary>
    /// Returns characters slices from string between two indexes.
    /// 
    /// If start or end are negative, their indexes will be calculated counting 
    /// back from the end of the source string. 
    /// If the end param is less than the start param, the Slice will return a 
    /// substring in reverse order.
    /// 
    /// <param name="source">String the extension method will operate upon.</param>
    /// <param name="startIndex">Starting index, may be negative.</param>
    /// <param name="endIndex">Ending index, may be negative).</param>
    /// </summary>
    public static string Slice(this string source, int startIndex, int endIndex = int.MaxValue)
    {
        // If startIndex or endIndex exceeds the length of the string they will be set 
        // to zero if negative, or source.Length if positive.
        if (source.ExceedsLength(startIndex)) startIndex = startIndex < 0 ? 0 : source.Length;
        if (source.ExceedsLength(endIndex)) endIndex = endIndex < 0 ? 0 : source.Length;

        // Negative values count back from the end of the source string.
        if (startIndex < 0) startIndex = source.Length + startIndex;
        if (endIndex < 0) endIndex = source.Length + endIndex;         

        // Calculate length of characters to slice from string.
        int length = Math.Abs(endIndex - startIndex);
        // If the endIndex is less than the startIndex, return a reversed substring.
        if (endIndex < startIndex) return source.Substring(endIndex, length).Reverse();

        return source.Substring(startIndex, length);
    }

    /// <summary>
    /// Reverses character order in a string.
    /// </summary>
    /// <param name="source"></param>
    /// <returns>string</returns>
    public static string Reverse(this string source)
    {
        char[] charArray = source.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }

    /// <summary>
    /// Verifies that the index is within the range of the string source.
    /// </summary>
    /// <param name="source"></param>
    /// <param name="index"></param>
    /// <returns>bool</returns>
    public static bool ExceedsLength(this string source, int index)
    {
        return Math.Abs(index) > source.Length ? true : false;
    }

因此,如果你有一个像“This is an extension method”这样的字符串,这里有一些示例和结果。

var s = "This is an extension method";
// If you want to slice off end characters, just supply a negative startIndex value
// but no endIndex value (or an endIndex value >= to the source string length).
Console.WriteLine(s.Slice(-5));
// Returns "ethod".
Console.WriteLine(s.Slice(-5, 10));
// Results in a startIndex of 22 (counting 5 back from the end).
// Since that is greater than the endIndex of 10, the result is reversed.
// Returns "m noisnetxe"
Console.WriteLine(s.Slice(2, 15));
// Returns "is is an exte"

希望这个版本对某些人有所帮助。如果不使用任何负数,它的操作就像正常的一样,并为超出范围的参数提供默认值。

public static string Last(this string source, int tailLength)
{
  return tailLength >= source.Length ? source : source[^tailLength..];
}
string var = "12345678";

var = var[^4..];

// var = "5678"

这是一个索引运算符,字面意思是“从end(^4)到end(..)取最后四个字符”

建议使用TakeLast方法,例如:new String(text.TakeLast(4).ToArray())