Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove substring if exists

I have 3 possible input cases

string input = "";        // expected result: ""
string input = "bar-foo"; // expected result: "foo"
string input = "foo";     // expected result: "foo"

And I have to remove everyting including the first separator char - if exists.

Working approach:

string output = input.Split('-').LastOrDefault();

I want to solve this without Split() - my NOT working approach:

string output = input.Substring(input.IndexOf('-') );

How can I handle the IndexOutOfRangeException / make this code work?

like image 896
Impostor Avatar asked Jun 04 '26 12:06

Impostor


1 Answers

Try to add 1:

string output = input.Substring(input.LastIndexOf('-') + 1);

If there's no - in the input, LastIndexOf returns -1 and so you'll have the entire string.

I've assumed that your are looking for input's suffix, that's why I've put LastIndexOf:

"123-456-789" -> "789"

If you want to cut off the prefix:

"123-456-789" -> "456-789"

please, change LastIndexOf into IndexOf

like image 93
Dmitry Bychenko Avatar answered Jun 07 '26 08:06

Dmitry Bychenko