Search code examples
c#stringreplacenon-repetitive

How to replace characters in a string in c#


So the title might be a little misleading, but hear me out. It's not as simple as I worded it in the title.

So I have a string say,

String dna="ACTG";

I have to convert said string into it's complement form. To complement said string, I have to replace all occurrences of "A" to "T", "C" to "G", "T" to "A" and "G" to "C". So the complement of the String should look like this:

String dnaComplement="TGAC";

How do I do this properly? E.G.

String temp = dna.Replace("A", "T");
temp = temp.Replace("T", "A");
temp = temp.Replace("C", "G");
temp = temp.Replace("G", "C");

This would have the output:

TCTC

Which is wrong. I'm a beginner at C# and I know a little about programming with it. I'm used to using java.


Solution

  • Something like:

    String dna="ACTG";
    String dnaComplement = "";
    
    foreach(char c in dna)
    {
      if (c == 'A') dnaComplement += 'T';
      else if (c == 'C') dnaComplement += 'G';
     // and so long
    }