-1

For Example: "I'm a word. change my char to new word"

i want replace "word" to "char" and replace "char" to "word"

result :"I'm a char. change my word to new char"

It is very important to me

so thanks.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
Hossein
  • 3,083
  • 3
  • 16
  • 33

2 Answers2

3

You can use a regular expression to match both words, so that you replace them in the same call. That way you avoid the problem with multiple replacements interfering with each other:

str = Regex.Replace(str, "(char|word)", m => m.Groups[0].Value == "char" ? "word" : "char");

This can easily be expanded to any number of replacements, that would otherwise conflict. You can also add the \b code in the regular expression so that it only matches whole words (and not for example a inside char). Example:

str = Regex.Replace(str, @"\b(a|char|word|new|my|to)\b", m => {
  string s = m.Groups[0].Value;
  return
    s == "a" ? "new" :
    s == "char" ? "word" :
    s == "word" ? "char" :
    s == "new" ? "a" :
    s == "my" ? "mine" :
    "with";
});

Result:

"I'm new char. change mine word with a char"
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

If you have 3 glasses, the 1st and last glas are filled with water and the other one is empty, how can you replace the water from glas 1 to glas 3? It's the same way for your problem.

First change word to to_replace (for example), than change char to word and change again to_replace to char.

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
  • The principle is sound, but you need to use a character that isn't used anywhere else in the string. Using `w` gives the result `"I'm a char. change my charord to nechar char"` – Guffa May 17 '15 at 09:25
  • Oke, I know that but the **w** is an example. You must use a char (or string) that isn't used. – H. Pauwelyn May 17 '15 at 09:27