我如何从c#中的字符串中获得最后四个字符?

假设我有一个字符串:

"34234234d124"

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

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

567608 次浏览
mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this?

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

mystring.Substring(mystring.Length - 4);

使用子字符串实际上是非常简短和可读的:

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

就是这样:

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

你可以使用扩展方法:

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);
string mystring = "34234234d124";
mystring = mystring.Substring(mystring.Length-4)

使用泛型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);
}
}

和string的一个特定的:

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

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

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

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

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

@".{4}\Z"
mystring = mystring.Length > 4 ? mystring.Substring(mystring.Length - 4, 4) : mystring;

下面是另一个应该不会太糟糕的替代方案(因为延迟执行):

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

虽然用于mystring.Last(4)的扩展方法显然是最干净的解决方案,尽管要做更多的工作。

好吧,我知道这是一篇旧文章,但为什么我们要重写框架中已经提供的代码呢?

我建议您添加一个对框架DLL "Microsoft. DLL "的引用。VisualBasic”

using Microsoft.VisualBasic;
//...


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

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

  1. 大于或匹配所要求的长度
  2. 比要求的长度短。

下面就是:

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

一个简单的解决方案是:

string mystring = "34234234d124";
string last4 = mystring.Substring(mystring.Length - 4, 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"

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

string var = "12345678";


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


// result = "5678"

你可以简单地使用c#的Substring方法。前女友。

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

它将返回结果0000。

假设你想要一个距离最后一个字符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);

定义:

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

用法:

GetLast("string of", 2);

结果:

你所要做的就是…

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

更新2020: c# 8.0最终使这变得容易:

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

你也可以用同样的方式切片数组,参见索引和范围

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

string var = "12345678";


var = var[^4..];


// var = "5678"

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

我想在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 doc参考指数和范围:

但是关于普遍性,我们还没有完成。到目前为止,每个例子都会抛出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:等价的变体与好旧Substring() 对于c# 6或7.x:
(你不能把它放在一个完整的字符串插值中,例如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)的扩展函数

对我来说,使用范围运算符是最简单的方法。不需要太多代码。

在你的情况下,你可以得到你想要的:

// the ^ operator indicates the element position from the end of a sequence
string str = "34234234d124"[^4..]
public static string Last(this string source, int tailLength)
{
return tailLength >= source.Length ? source : source[^tailLength..];
}
            string x = "34234234d124";


string y = x.Substring(x.Length - 4);

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

using System.Linq;


string.Concat("123".TakeLast(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&;如果它们被存储为数字,就会这样排序。