Karlx Swanovski
Karlx Swanovski

Reputation: 2989

Substring with repeating character

How I will substring this sample combobox items

E11-143 - America           -->    America 
JC - Political theory       -->    Political theory

I tried this:

string test = comboBox1.Text.Substring(comboBox1.Text.IndexOf('-') + 1).Trim();

But this is the result

E11-143 - America           -->    143 - America 
JC - Political theory       -->    Political theory

Upvotes: 1

Views: 129

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460340

You can use String.IndexOf + Substring. But you need to search for " - " instead for - (note the white-spaces)

int index = text.IndexOf(" - ");
string result = null;
if(index >= 0)
     result = text.Substring(index + " - ".Length);

or String.Split

text.Split(new[]{" - "},StringSplitOptions.None).Last();

The IndexOf approach is more efficient whereas the Split is more readable.

Upvotes: 1

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33391

Another variation:

var str = "E11-143 - America";
var val = str.Split('-').LastOrDefault().Trim();

Upvotes: 2

I4V
I4V

Reputation: 35363

var str = "E11-143 - America";
var newstr = str.Substring(str.LastIndexOf("-")+1).Trim();

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149078

Use LastIndexOf to get the index of the last occurrence of a character:

string test = comboBox1.Text.Substring(comboBox1.Text.LastIndexOf('-') + 1).Trim();

Upvotes: 3

Related Questions