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.
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.
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"
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.