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

假设我有一个string:

string mystring = "34234234d124"; 

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

是否有可能得到这个结果与C#的一个expression式?

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

如果你是积极的,你的string的长度至less是4,那么它甚至更短:

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

好吧,所以我看到这是一个旧的post,但为什么我们重写框架中已经提供的代码?

我build议你添加一个引用框架DLL“Microsoft.VisualBasic”

 using Microsoft.VisualBasic; //... string value = Strings.Right("34234234d124", 4); 
 string mystring = "34234234d124"; mystring = mystring.Substring(mystring.Length-4) 

使用Substring实际上非常短而且可读:

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

这是另一个不应该performance得太差的select(因为延期执行 ):

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

尽pipe目的mystring.Last(4)的扩展方法显然是最干净的解决scheme,尽pipe有点工作。

一个简单的解决scheme是:

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

你可以简单地使用C#的Substring方法。 例如。

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

它将返回结果0000。

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

这只是:

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

与之前的一些答案相比,主要的区别在于这段代码在inputstring是:

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

这对任何长度的string都不会失败。

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

这对于手头的任务来说可能是过度的,但是如果需要额外的validation,它可能会被添加到正则expression式中。

编辑:我认为这个正则expression式会更有效率:

 @".{4}\Z" 

使用通用的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()); } 

定义:

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

我把从各种来源修改过来的一些代码放在一起,这些代码将得到你想要的结果,而且还做了更多的事情。 我已经允许负int值,int值超过了string的长度,并为结束索引小于开始索引。 在最后一种情况下,该方法返回一个反序子串。 有很多意见,但让我知道,如果有什么不清楚或只是疯了。 我正在玩这个,看看我可以用它来做什么。

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

所以,如果你有一个像“这是一个扩展方法”的string,这里有一些例子和结果期望。

 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" 

假设你想要一个string位于距最后一个字符10个字符的string之间,而你只需要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);