1

Everyone knows how to replace a character in a string with:

string text = "Hello World!";
text = text.Replace("H","J");

but what I need is to replace multiple characters in a string something like:

string text = textBox1.Text;
text = text.Replace("a","b")
text = text.Replace("b","a")

now the result is aa , but if the user types ab I want the result to be ba

3
  • Have you looked at Regex.Replace ? One of the overloads accept a delegate that will be called for each match. Commented May 18, 2016 at 17:57
  • foreach(var c in string){do new string} Commented May 18, 2016 at 17:58
  • 3
    You haven't asked a question. A list of your wants is not a question. What's your question? Commented May 18, 2016 at 18:06

4 Answers 4

4

There's multiple ways to do this.

Using a loop

char[] temp = input.ToCharArray();
for (int index = 0; index < temp.Length; index++)
    switch (temp[index])
    {
        case 'a':
            temp[index] = 'b';
            break;
        case 'b':
            temp[index] = 'a';
            break;
    }
string output = new string(temp);

This will simply copy the string to a character array, fix each character by itself, then convert the array back into a string. No risk of getting any of the characters confused with any of the others.

Using a regular expression

You can exploit this overload of Regex.Replace:

public static string Replace(
    string input,
    string pattern,
    MatchEvaluator evaluator
)

This takes a delegate that will be called for each match, and return the final result. The delegate is responsible for returning what each match should be replaced with.

string output = Regex.Replace(input, ".", ma =>
{
    if (ma.Value == "a")
        return "b";
    if (ma.Value == "b")
        return "a";
    return ma.Value;
});
Sign up to request clarification or add additional context in comments.

Comments

0

For your particular requirement I would suggest you to use like the following:

string input = "abcba";        
string outPut=String.Join("",input.ToCharArray()
                             .Select(x=> x=='a'? x='b':
                             (x=='b'?x='a':x))
                             .ToArray()); 

The output string will be bacab for this particular input

1 Comment

@GiorgiNakeuri : Nice spot; could you please check the updates
0

Do not call String.Replace multiple times for the same string! It creates a new string every time (also it has to cycle through the whole string every time) causing memory pressure and processor time waste if used a lot.

What you could do:

Create a new char array with the same length as the input string. Iterate over all chars of the input strings. For every char, check whether it should be replaced. If it should be replaced, write the replacement into the char array you created earlier, otherwise write the original char into that array. Then create a new string using that char array.

string inputString = "aabbccdd";
char[] chars = new char[inputString.Length];

for (int i = 0; i < inputString.Length; i++)
{
    if (inputString[i] == 'a')
    {
        chars[i] = 'b';
    }
    else if (inputString[i] == 'b')
    {
        chars[i] = 'a';
    }
    else
    {
        chars[i] = inputString[i];
    }
}

string outputString = new string(chars);

Consider using a switch when intending to replace a lot of different characters.

Comments

0

Use should use StringBuilder when you are concatenating many strings in a loop like this, so I suggest the following solution:

StringBuilder sb = new StringBuilder(text.Length);

foreach(char c in text)
{
   sb.Append(c == 'a' ? 'b' : 'a');
}

var result = sb.ToString();

1 Comment

You should set the initial capacity of the StringBuilder to the length of the input string to prevent unnecessary array re-allocations. (The default capacity of StringBuilder is 16, every time that buffer is full, a new buffer with double the current capacity is allocated.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.