假设我有一个字符串:

"34234234d124"

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

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


当前回答

string var = "12345678";

if (var.Length >= 4)
{
    var = var.substring(var.Length - 4, 4)
}

// result = "5678"

其他回答

更新2020:c# 8.0终于让这变得容易:

> "C# 8.0 finally makes this easy"[^4..]
"easy"

您还可以以相同的方式对数组进行切片,请参阅索引和范围。

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

使用泛型Last<T>。这将适用于任何IEnumerable,包括string。

public static IEnumerable<T> Last<T>(this IEnumerable<T> enumerable, int nLastElements)
{
    int count = Math.Min(enumerable.Count(), nLastElements);
    for (int i = enumerable.Count() - count; i < enumerable.Count(); i++)
    {
        yield return enumerable.ElementAt(i);
    }
}

和string的一个特定的:

public static string Right(this string str, int nLastElements)
{
    return new string(str.Last(nLastElements).ToArray());
}

我想扩展现有的答案,提到在c# 8或更高版本中使用新的范围:为了使代码可用于所有可能的字符串,甚至那些小于4的字符串,需要某种形式的条件!如果您想复制代码,我建议使用示例5或6。

string mystring ="C# 8.0 finally makes slicing possible";

1:切片取结尾部分-通过指定从开始省略多少字符-这是VS 2019的建议:

string example1 = mystring[Math.Max(0, mystring.Length - 4)..] ;

2:切片取结尾部分-通过指定从结尾取多少字符:

string example2 = mystring[^Math.Min(mystring.Length, 4)..] ;

3:切片取结束部分-通过用?:操作符替换Max/Min:

string example3 = (mystring.length > 4)? mystring[^4..] : mystring); 

就我个人而言,我更喜欢第二种和第三种变体。

索引和范围的MS文档参考:

空吗?但是,关于普遍性,我们还没有完成。到目前为止,每个例子都会抛出null字符串的异常。考虑null(如果你在c# 8或更高版本中不使用不可空字符串),并且不使用'if'(经典示例'with if'已经在另一个答案中给出),我们需要:

4:切片考虑空-通过指定省略多少字符:

string example4 = mystring?[Math.Max(0, mystring.Length - 4)..] ?? string.Empty;

5:切片考虑空-通过指定多少字符采取:

string example5 = mystring?[^Math.Min(mystring.Length, 4)..] ?? string.Empty;

6:使用?:操作符(和另外两个'?'操作符;-): (你不能把它放在一个完整的字符串插值中,例如WriteLine。)

string example6 = (mystring?.Length > 4) ? filePath[^4..] : mystring ?? string.Empty;

7: c# 6或7.x的Substring()的等效变体: (你不能把它放在一个完整的字符串插值中,例如WriteLine。)

string example7 = (mystring?.Length > 4) ? mystring.Substring(mystring.Length- 4) : mystring ?? string.Empty;

优雅降级? 我喜欢c#的新特性。像上一个例子那样把它们放在一行可能看起来有点过分。我们最后有点perl ' ish,不是吗? 但它是一个学习的好例子,我可以在一个测试过的库方法中使用它一次。 更好的是,如果我们愿意,我们可以在现代c#中摆脱null,并避免所有这些特定于null的处理。

这样的库/扩展方法作为一个快捷方式是非常有用的。尽管c#很先进,但你必须自己编写代码,这样才能更容易使用,而不是重复上面的代码来处理每个小的字符串操作。

我是开始学习BASIC语言的人之一,40年前就已经有了Right$(,)。有趣的是,在VB和c#中仍然可以使用string . right(,),正如在另一个答案中所显示的那样。

c#选择了精确而不是优雅的退化(与旧的BASIC相反)。 所以在这些答案中复制任何你喜欢的合适的变体,并为自己定义一个优雅的快捷函数,我的是一个名为RightChars(int)的扩展函数。

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

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