0

I need to replace multiple characters in C# using .replace without creating a loop resulting in final string of the final character in the loop

Example code:

string t1="ABCD";
t1.Replace('A','B').Replace('B','C').Replace('C','D').Replace('D','E');

Result: EEEE

Expected result: BCDE

How do I get the expected result, I do this for a large number of characters in a string <=100 so I need a easy way. Can I do it with replace method or is there some other way?

10
  • 1
    Think about what is happening at each call to replace, see what string you have at the end of each call. Then you will see why it is behaving that way. Why not just remove 'A' from the front and add 'E' at the end. Just a thought! Commented Mar 1, 2017 at 1:44
  • i understand the way it behaves, i want to know if there is some way to overcome that... Commented Mar 1, 2017 at 1:46
  • and get the expected result.. Commented Mar 1, 2017 at 1:47
  • 2
    In this particular example, it should work if you just reverse the order of your Replace(...) calls. Commented Mar 1, 2017 at 1:47
  • @Augustine just for this particular example! Commented Mar 1, 2017 at 1:50

5 Answers 5

2

If you don't want to write it yourself, probably the simplest way to code it would be with regexes:

Regex.Replace(mystring, "[ABCD]", s =>
{
    switch (s)
    {
        case "A": return "B";
        case "B": return "C";
        case "C": return "D";
        case "D": return "E";
        default: return s;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

Before going to the answer let me describe what went wrong in your case, Actually the replace operations returns a new instance of the string so after the first replace(t1.Replace('A','B') the resulting string becomes BBCD(A is replaced with B) and you are performing the next replace operation in this string, hence every B will be replaced with C. so before final Replace your input string becomes DDDD.

I've a simple solution using LINQ with String.Join, You can take a look into the working example here

string inputString = "ABCD";
var ReplacedString = String.Join("", inputString.Select(x => x == 'A' ? 'B' : 
                                                    x == 'B' ? 'C' :
                                                    x == 'C' ? 'D' : 
                                                    x == 'D' ? 'E' : 
                                                    x));

Comments

0

In this particular example, it should work if you just reverse the order of your Replace(...) calls.

string t1="ABCD";
t1.Replace('D','E').Replace('C','D').Replace('B','C').Replace('A','B');

2 Comments

Beat me by about 30 seconds.
Reversing that works for the specific example, but it obviously won't work if the substitutions form a loop.
0

This might do the trick for you

string t1 = "ABCD";
var ans = string.Join("", t1.Select(x => x = (char) ((int) x + 1)));

This code will give the next character of the string. But the case of the last character of the alphabet which is z and Z this will gonna fail. Fail means it would not be a or A instead it will give { and [. But most of the cases this could be used to get the next character in the string.

Comments

0

The answers already posted will solve the immediate example that you give, but you also say that you have to do this for a large number of characters in a string. I may be misunderstanding your requirements, but it sounds like you are just trying to "increment" each letter. That is, A becomes B, I becomes J, etc.

If this is the case, a loop (not sure why you want to avoid loops; they seem like the best option here) will be much better than stringing a bunch of replaces together, especially for longer strings.

The below code assumes your only input will be capital latin letters, and for the letter Z, I've just wrapped the alphabet, so it will be replaced with A.

string t1 = "ABCDEFGXYZ";
StringBuilder sb = new StringBuilder();
foreach (char character in t1)
{
    if (character == 'Z')
    {
        sb.Append('A');
    }
    else
    {
        sb.Append((Char)(Convert.ToUInt16(character) + 1));
    }
}

Console.WriteLine(sb.ToString());

The following code takes input ABCDEFGXYZ and outputs BCDEFGHYZA. This is extensible to much larger inputs as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.