如何从C#中的字符串中获取最后四个字符?

问题描述 投票:267回答:18

假设我有一个字符串:

string mystring = "34234234d124";

我想得到这个字符串的最后四个字符是"d124"。我可以使用SubString,但它需要几行代码。

是否可以使用C#在一个表达式中获得此结果?

c# string
18个回答
352
投票
mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this?

如果你是正面的,你的字符串长度至少为4,那么它甚至更短:

mystring.Substring(mystring.Length - 4);

7
投票
mystring = mystring.Length > 4 ? mystring.Substring(mystring.Length - 4, 4) : mystring;

6
投票

就是这样:

int count = 4;
string sub = mystring.Substring(mystring.Length - count, count);

6
投票

与之前的一些答案相比,主要区别在于,当输入字符串为:时,这段代码会考虑:

  1. 空值
  2. 长度超过或匹配要求的长度
  3. 比请求的长度短。

这里是:

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

    public static string MyLast(this string str, int length)
    {
        if (str == null)
            return null;
        else if (str.Length >= length)
            return str.Substring(str.Length - length, length);
        else
            return str;
    }
}

3
投票

对于任何长度的字符串,这都不会失败。

string mystring = "34234234d124";
string last4 = Regex.Match(mystring, "(?!.{5}).*").Value;
// last4 = "d124"
last4 = Regex.Match("d12", "(?!.{5}).*").Value;
// last4 = "d12"

这对于手头的任务来说可能有些过分,但如果需要进行额外的验证,则可以将其添加到正则表达式中。

编辑:我认为这个正则表达式会更有效:

@".{4}\Z"

3
投票

使用通用的Last<T>。这适用于任何IEnumerable,包括字符串。

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

还有一个特定的字符串:

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

3
投票

定义:

public static string GetLast(string source, int last)
{
     return last >= source.Length ? source : source.Substring(source.Length - last);
}

用法:

GetLast("string of", 2);

结果:


1
投票

我将从各种来源修改过的代码汇集在一起​​,这些代码将获得您想要的结果,并且还可以做更多的事情。我允许使用负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;
    }

因此,如果你有一个像“这是一个扩展方法”这样的字符串,这里有一些例子和结果。

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"

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


1
投票
string var = "12345678";

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

// result = "5678"

1
投票

假设您希望字符串位于一个字符串之间,该字符串与最后一个字符相距10个字符,而您只需要3个字符。

让我们说StreamSelected = "rtsp://72.142.0.230:80/SMIL-CHAN-273/4CIF-273.stream"

在上面,我需要提取我将在数据库查询中使用的"273"

        //find the length of the string            
        int streamLen=StreamSelected.Length;

        //now remove all characters except the last 10 characters
        string streamLessTen = StreamSelected.Remove(0,(streamLen - 10));   

        //extract the 3 characters using substring starting from index 0
        //show Result is a TextBox (txtStreamSubs) with 
        txtStreamSubs.Text = streamLessTen.Substring(0, 3);

200
投票

你可以使用extension method

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

44
投票

好的,所以我看到这是一篇旧帖子,但为什么我们要重写已在框架中提供的代码?

我建议您添加对框架DLL“Microsoft.VisualBasic”的引用

using Microsoft.VisualBasic;
//...

string value = Strings.Right("34234234d124", 4);

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

25
投票

使用Substring实际上非常简短和可读:

 var result = mystring.Substring(mystring.Length - Math.Min(4, mystring.Length));
 // result == "d124"

23
投票

你所要做的就是......

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

16
投票

这是另一种不应该表现得太差的选择(因为deferred execution):

new string(mystring.Reverse().Take(4).Reverse().ToArray());

虽然mystring.Last(4)的扩展方法显然是最干净的解决方案,尽管还有一些工作要做。


16
投票

你可以简单地使用C#的Substring方法。对于前者

string str = "1110000";
string lastFourDigits = str.Substring((str.Length - 4), 4);

它将返回结果0000。


11
投票

一个简单的解决方案是:

string mystring = "34234234d124";
string last4 = mystring.Substring(mystring.Length - 4, 4);
© www.soinside.com 2019 - 2024. All rights reserved.