How to remove letters from the string and leave just 3 last chars
Input:
foobar
Output:
bar
I tried:
string.Concat("foobar".Reverse().Skip(3).Reverse());
But that removes last 3 lines not keeps them
How to remove letters from the string and leave just 3 last chars
Input:
foobar
Output:
bar
I tried:
string.Concat("foobar".Reverse().Skip(3).Reverse());
But that removes last 3 lines not keeps them
Well, you can try Substring
: if source
is long enough we get Substring
otherwise leave source
intact:
string source = ...
string result = source.Length > 3
? source.Substring(source.Length - 3)
: source;
Or even
string result = source.Substring(Math.Max(0, source.Length - 3));
Since C# 8, you can also use range syntax:
string result = source.Length > 3 ? source[^3..] : source;
or:
string result = source[^Math.Min(3, source.Length)..];
[^3..]
is a range which means "start 3 elements from the end, and keep going until the end".
There is a one line solution as well. Just check whether source string has enough length to get last 3 characters using Substring
or leave string as is. Math.Max
function will return a correct index
var str = "foobar";
var result = str.Substring(Math.Max(0, str.Length - 3));