Replace Nth in String?

B

bdwise

I have this value

abcdef

And sometimes I want to replace "b" with "x" and sometimes I want to
replace "f" with "x" and sometimes I want to replace "e" with "x". I
want to replace characters in the string by their position, not their
ASCII content.

What is a common way to do that without using a regex?
 
J

Joe Mayo

How about string.Replace():

string letters = "abcdef";

string newLetters = letters.Replace('b', 'x');

Joe
 
B

Bill Styles

bdwise said:
I have this value

abcdef

And sometimes I want to replace "b" with "x" and sometimes I want to
replace "f" with "x" and sometimes I want to replace "e" with "x". I
want to replace characters in the string by their position, not their
ASCII content.

two ways I know of offhand

string s = "abcdef";
s = s.Substring(0,1) + "x" + s.Substring(2);

or use a System.Text.Stringbuilder object

System.Text.StringBuilder s=new System.Text.StringBuilder("abcde");
s.Remove(1,1);
s.Insert(1,"x");
 
B

Brian W

In addition, you could always use the indexer too.

StringBuilder sb = new StringBuilder("abcdef");
sb[2]='x';


Good luck
Brian W
 
B

Bill Styles

Brian W said:
In addition, you could always use the indexer too.

StringBuilder sb = new StringBuilder("abcdef");
sb[2]='x';

d'oh! I can't believe I missed that one especially since it's got to be
more efficient than the other options.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top