J.Danely
J.Danely

Reputation: 37

C# replace different characters in a string

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

Upvotes: 1

Views: 2829

Answers (4)

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35790

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();

Upvotes: 0

Domi
Domi

Reputation: 292

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.

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29036

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

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391724

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;
});

Upvotes: 3

Related Questions