1

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

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
John Bielowski
  • 199
  • 2
  • 11

3 Answers3

8

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));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
7

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".

canton7
  • 37,633
  • 3
  • 64
  • 77
  • I love this state of the art code (ranges) ;) – Dmitry Bychenko Mar 05 '20 at 12:44
  • Out of interest, I looked at the IL generated for this, and it does actually translate it into a call to `string.Substring()` so this is pretty optimal. – Matthew Watson Mar 05 '20 at 12:52
  • Yeah, it's got special support for arrays and strings, and it fakes indexers which take a range if the type has a suitable `Slice` method, and a `Length` or `Count` property – canton7 Mar 05 '20 at 12:56
3

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));
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66