简体   繁体   中英

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? EG

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.

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
}

You can use dictionary of complements and then use Linq Select :

var complements = new Dictionary<char, char>
    {
        { 'A', 'T' },
        { 'C', 'G' },
        { 'G', 'C' },
        { 'T', 'A' },
    };

var original = "TGAC";
var transformated = string.Concat(original.Select(c => (complements.ContainsKey(c)) ? complements[c] : c));

I would do this:

var complements = new Dictionary<char, char>
{
    { 'A', 'T' },
    { 'C', 'G' },
    { 'G', 'C' },
    { 'T', 'A' },
};

string dna = "ACTG";

string dnaComplement =
    new string(
        dna
            .ToCharArray()
            .Select(x => complements[x])
            .ToArray());

Replace with unique tokens so for example A-->l, T-->m C-->n G-->o. Now you can substitute for each token without changing any other - so L-->T etc.

Change the characters first to something else.

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

This code from you:

String temp = dna.Replace("A", "T"); // A's are changed to T...
temp = temp.Replace("T", "A"); // ... but your just obtained 'T's are changed back to A
// ...

Each of the answers above is correct and solves your problem, but if you're going to do a lot of replacing frequently, consider using a StringBuilder . string.Replace() returns a new string instance every time you call it, the old instance becomes garbage and has to be collected. This can lead to a performance penalty for your app.

I would do this:

var complement = dna.Select(c =>
{
    switch (c)
    {
        case 'A': return 'T';
        case 'T': return 'A';
        case 'C': return 'G';
        case 'G': return 'C';
        default: throw new ArgumentException(); // or whatever
    }
});

EDIT: With this you get an IEnumerbale<char> . To transform this back to a string see this Answer .

Like Michal Hosala said, you have to make clear what is the definition of the complement. I will assume that you split the string in 2 equal parts and the first char in the first string is the complement of the first char in the second string.

I also treated the case when you have an odd number of chars, the complement of "ACXTG" will be "TGXAC".

string dna = "ACTG";
string dnaComplement = "";

if (dna.Length % 2 == 1)
    dnaComplement += dna[dna.Length / 2];
for (int i = 0; i < dna.Length / 2; i++)
    dnaComplement = dna[dna.Length - i - 1] + dnaComplement + dna[i];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM