假设我有一个字符串:

"34234234d124"

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

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


当前回答

你所要做的就是…

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

其他回答

你可以使用扩展方法:

public static class StringExtension
{
    public static string GetLast(this string source, int tail_length)
    {
       if(tail_length >= source.Length)
          return source;
       return source.Substring(source.Length - tail_length);
    }
}

然后调用:

string mystring = "34234234d124";
string res = mystring.GetLast(4);

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

string mystring = "34234234d124";
mystring = mystring.Substring(mystring.Length-4)

这工作得很好,因为如果字符串中的字符比请求的数量少,也不会出现错误。

using System.Linq;

string.Concat("123".TakeLast(4));

我将从不同来源修改的一些代码放在一起,可以得到您想要的结果,并且还可以做更多的事情。我已经允许负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"

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