.replace()函数无法正确交换字符

时间:2019-03-21 13:03:00

标签: java string replace

我正在编写一个将特定字符替换为其他字符的函数

public static String makeComplement(String dna) {
    if(dna.contains("A")|| (dna.contains("T") ||(dna.contains("G") ||(dna.contains("C") ) )) ){
        dna = dna.replace('A' , 'T');
        dna = dna.replace('T' , 'A');
        dna = dna.replace('G' , 'C');
        dna = dna.replace('C' , 'G');

        System.out.println(dna);
    }
    return dna;
}

public static void main(String[] args) {
    String ex ="GTACTCC";
    System.out.println(ex);

    makeComplement(ex);
}

它代替了A中的T和G中的C,但保持A和G不变。

2 个答案:

答案 0 :(得分:2)

当然可以。

dna = dna.replace('A' , 'T'); // replaces As with Ts
dna = dna.replace('T' , 'A'); // replace Ts with As (including the As that 
                              // were replaced with Ts)
dna = dna.replace('G' , 'C'); // replaces Gs with Cs
dna = dna.replace('C' , 'G'); // replace Cs with Gs (including the Gs that 
                              // were replaced with Cs)

如果您想将As与Ts和Gs与Cs交换,则可能应该使用一些中间字母:

dna = dna.replace('A' , 'X');
dna = dna.replace('T' , 'A'); // only original Ts will become As 
dna = dna.replace('X' , 'T');
dna = dna.replace('G' , 'Y');
dna = dna.replace('C' , 'G'); // only original Cs will become Gs
dna = dna.replace('Y' , 'C');

编辑:正如Mike所评论的,无需使用replace方法,您可以更有效地进行此替换:

StringBuilder sb = new StringBuilder (dna.length());
for (char c : dna.toCharArray()) {
    if (c == 'A')
        sb.append('T');
    else if (c == 'T')
        sb.append('A');
    else if (c == 'G')
        sb.append('C');
    else if (c == 'C')
        sb.append('G');
} 
dna = sb.toString();

答案 1 :(得分:2)

调用String.contains和/或String.replace可能会扫描整个字符串,因此多次调用它可能会花费很长的字符串。

为什么不一次完成所有替换操作:

// Copy the original DNA string to a new mutable char array
char[] dnaCopy = dna.toCharArray();

// Examine each character of array one time only and replace
// as necessary
for(int i = 0; i < dnaCopy.length; i++) {
  if(dnaCopy[i] == 'A') {
     dnaCopy[i] = 'T';
  }
  else if(dnaCopy[i] == 'T') {
     dnaCopy[i] = 'A';
  }
  else if(dnaCopy[i] == 'G') {
     dnaCopy[i] = 'C';
  }
  else if(dnaCopy[i] == 'C') {
     dnaCopy[i] = 'G';
  }
}

// Now you can do whatever you want with dnaCopy: make a new String, etc

对于长字符串,此方法应具有更高的性能,并且可以使用分而治之的方法扩大规模(即,您可以让2个线程同时在数组的一半上工作)。