DaBears
DaBears

Reputation: 1743

Inserting a special character at the proper place in a string using C#

If I have a string like:

"SMITH 10-12 4-11H2"

And I want to modify this string to have a # after the first dash AND the following space to be like:

"SMITH 10-12 #4-11H2"

What is the best way to do this using C#?

Upvotes: 1

Views: 115

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273244

Without any checks it could look like this:

int pos1 = text.IndexOf('-');    
int pos2 = text.IndexOf(' ', pos1);    
string result = text.Insert(pos2+1, "#");

Upvotes: 4

Related Questions