How do I get the last four characters from a string in C#?
假设我有一根绳子:
1 | string mystring ="34234234d124"; |
我想得到这个字符串的最后四个字符,即
是否可以在一个表达式中使用c_获得此结果?
1 | mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this? |
如果你是正的,你的线的长度至少是4,那么它会更短:
1 | mystring.Substring(mystring.Length - 4); |
您可以使用扩展方法:
1 2 3 4 5 6 7 8 9 | 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); } } |
然后呼叫:
1 2 | string mystring ="34234234d124"; string res = mystring.GetLast(4); |
好吧,我看到这是一篇老文章,但是为什么我们要重写框架中已经提供的代码呢?
我建议您添加对框架dll"microsoft.VisualBasic"的引用。
1 2 3 4 | using Microsoft.VisualBasic; //... string value = Strings.Right("34234234d124", 4); |
1 2 | string mystring ="34234234d124"; mystring = mystring.Substring(mystring.Length-4) |
使用子字符串实际上非常短且可读:
1 2 | var result = mystring.Substring(mystring.Length - Math.Min(4, mystring.Length)); // result =="d124" |
你所要做的就是……
1 | String result = mystring.Substring(mystring.Length - 4); |
另一种选择是,不应表现太差(因为延迟执行):
尽管
您可以简单地使用c的
1 2 | string str ="1110000"; string lastFourDigits = str.Substring((str.Length - 4), 4); |
它将返回结果0000。
一个简单的解决方案是:
1 2 | string mystring ="34234234d124"; string last4 = mystring.Substring(mystring.Length - 4, 4); |
1 | mystring = mystring.Length > 4 ? mystring.Substring(mystring.Length - 4, 4) : mystring; |
与前面的一些答案相比,主要的区别在于,当输入字符串是:
这里是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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; } } |
就是这样:
1 2 | int count = 4; string sub = mystring.Substring(mystring.Length - count, count); |
这对于任何长度的字符串都不会失败。
1 2 3 4 5 | string mystring ="34234234d124"; string last4 = Regex.Match(mystring,"(?!.{5}).*").Value; // last4 ="d124" last4 = Regex.Match("d12","(?!.{5}).*").Value; // last4 ="d12" |
对于手头的任务来说,这可能是多余的,但是如果需要额外的验证,则可以将其添加到正则表达式中。
编辑:我认为这个regex会更有效:
1 | @".{4}\Z" |
使用通用的
1 2 3 4 5 6 7 8 | 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); } } |
一个特定的字符串:
1 2 3 4 | public static string Right(this string str, int nLastElements) { return new string(str.Last(nLastElements).ToArray()); } |
定义:
1 2 3 4 | public static string GetLast(string source, int last) { return last >= source.Length ? source : source.Substring(source.Length - last); } |
用途:
1 | GetLast("string of", 2); |
结果:
属于
我收集了一些从不同来源修改的代码,这些代码将得到你想要的结果,并且做了更多的工作。我允许使用负的int值、超过字符串长度的int值以及小于起始索引的结束索引。在最后一种情况下,该方法返回一个颠倒顺序的子字符串。有很多评论,但如果有什么不清楚或只是疯狂的话,请告诉我。我在玩这个,想看看我能用它做什么。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | /// <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; } |
所以,如果您有一个类似"这是一个扩展方法"的字符串,这里有一些例子和结果。
1 2 3 4 5 6 7 8 9 10 11 | 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 2 3 4 5 6 7 8 | string var ="12345678"; if (var.Length >= 4) { var = var.substring(var.Length - 4, 4) } // result ="5678" |
假设您希望字符串位于距最后一个字符10个字符的字符串之间,而您只需要3个字符。
比如说
在上面,我需要提取我将在数据库查询中使用的
1 2 3 4 5 6 7 8 9 | //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); |