Suppose I have a string:
\"34234234d124\"
I want to get the last four characters of this string which is \"d124\"
. I can use <
Suggest using TakeLast method, for example: new String(text.TakeLast(4).ToArray())
This won't fail for any length string.
string mystring = "34234234d124";
string last4 = Regex.Match(mystring, "(?!.{5}).*").Value;
// last4 = "d124"
last4 = Regex.Match("d12", "(?!.{5}).*").Value;
// last4 = "d12"
This is probably overkill for the task at hand, but if there needs to be additional validation, it can possibly be added to the regular expression.
Edit: I think this regex would be more efficient:
@".{4}\Z"
Definition:
public static string GetLast(string source, int last)
{
return last >= source.Length ? source : source.Substring(source.Length - last);
}
Usage:
GetLast("string of", 2);
Result:
of
Use a generic Last<T>
. That will work with ANY IEnumerable
, including 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);
}
}
And a specific one for string:
public static string Right(this string str, int nLastElements)
{
return new string(str.Last(nLastElements).ToArray());
}
You can use an 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);
}
}
And then call:
string mystring = "34234234d124";
string res = mystring.GetLast(4);
A simple solution would be:
string mystring = "34234234d124";
string last4 = mystring.Substring(mystring.Length - 4, 4);