Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Today i have a unique requirement which i am going to explain with an example

My String
string s = "aaaabcc";

Now i want to use 2 replace functions at same time. so, answer would be like this:-
OUTPUT
ccccbaa

Till now i don't know how to start as when i write
string s = "aaaabcc";
s = s.Replace("a","c").Replace("c","a");

the answer goes wrong cause last replace function removes the newly added char.
Can anyone help me here any piece of code snippet would be helpful



Thanks in advance
Posted

1 solution

Since you are replacing the same chars then you should use a temp char:
C#
string s = "aaaabcc";
s = s.Replace("a","x");
s = s.Replace("c","a");
s = s.Replace("x","c");


Edit:
Use the following code:
C#
string s = "aaaabcc";
StringBuilder sb = new StringBuilder();
foreach(var c in s)
{
    if(c == 'a')
        sb.Append('c');
    else if(c == 'c')
        sb.Append('a');
    else
        sb.Append(c);
}
string outs = sb.ToString();
 
Share this answer
 
v2
Comments
agent_kruger 31-Oct-14 7:10am    
cant sir because every char in the char map has already been taken
Mehdi Gholam 31-Oct-14 7:19am    
Use a punctuation character like | ~ ! etc.
agent_kruger 31-Oct-14 7:59am    
sir as i have said that every char in the char space chart is being used in the software that is why i cannot use this method
agent_kruger 31-Oct-14 7:16am    
sir, any other idea about this question?
Mehdi Gholam 31-Oct-14 8:12am    
See the update.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900