.replace()函数不能正确交换字符

问题描述 投票:0回答:2

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

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不变。

java string replace
2个回答
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)

如果你想用Cs交换As和Ts和Gs,你应该使用一些中间字母:

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');

编辑:正如迈克评论的那样,如果没有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();

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个线程)。

© www.soinside.com 2019 - 2024. All rights reserved.