Impostor
Impostor

Reputation: 2050

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?

Upvotes: 3

Views: 6238

Answers (3)

Manish Singh
Manish Singh

Reputation: 1004

i think you should use Contains Method to identify - is available or not.

string a = "";

    if (a.Contains("-"))
    {
       string output = input.Substring(input.LastIndexOf('-') + 1);
    }

Upvotes: 2

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

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

Upvotes: 9

Neil
Neil

Reputation: 11889

Why not just remove it from the string without checking:

input = input.Replace("-foo", string.Empty);

Upvotes: 3

Related Questions