replace characters in a string

C#:

using System;
using System.Linq;

public class DnaStrand
{
    public static string MakeComplement(string dna)
    {
        return string.Concat(dna.Select(GetComplement));
    }

    public static char GetComplement(char symbol)
    {
        switch (symbol)
        {
            case 'A':
                return 'T';
            case 'T':
                return 'A';
            case 'C':
                return 'G';
            case 'G':
                return 'C';
            default:
                throw new ArgumentException();
        }
    }
}

Java: 

public class DnaStrand {
  public static String makeComplement(String dna) {
    char[] chars = dna.toCharArray();
    for(int i = 0; i < chars.length; i++) {
      chars[i] = getComplement(chars[i]);
    }
    
    return new String(chars);
  }
  
  private static char getComplement(char c) {
    switch(c) {
      case 'A': return 'T';
      case 'T': return 'A';
      case 'C': return 'G';
      case 'G': return 'C';
    }
    return c;
  }
}

JS:

function DNAStrand(dna) {
  return dna.replace(/./g, function(c) {
    return DNAStrand.pairs[c]
  })
}

DNAStrand.pairs = {
  A: 'T',
  T: 'A',
  C: 'G',
  G: 'C',
}
posted on 2019-01-21 16:58  小兔无情  阅读(206)  评论(0编辑  收藏  举报