gpt4 book ai didi

Java 使用数组连接字符串

转载 作者:行者123 更新时间:2023-12-01 18:40:06 27 4
gpt4 key购买 nike

我知道有一个支持处理生物信息的包,例如 Biojava ,但我想编写一个简单的代码,将 DNA 序列转换为其补体序列

这是我的代码...

public class SeqComplement{
static String sequence ;
String Complement(String sequence){
// this.sequence = sequence;
// String complement;
// complement = "N";
// for(int i = 0 ; i< sequence.length() ; i++){
String[] raw = new String[sequence.length()];
String[] complement = new String[sequence.length()];
String ComplementSeq = "N";
for(int i = 0 ; i <sequence.length() ; i++){
String sub = sequence.substring(i,i+1);
raw[i] = sub;
}
for(int j = 0 ; j < sequence.length();j++){
if(raw[j] == "A"){
complement[j] = "T";
}
else if (raw[j] == "T"){
complement[j] = "A";
}
else if (raw[j] == "G"){
complement[j] = "C";
}
else if (raw[j] == "C"){
complement[j] = "G";
}
else{
complement[j] = "N";
}
}
for(int k = 0 ; k < complement.length ; k++){
ComplementSeq+=complement[k];
}
return ComplementSeq.substring(1);
}


public static void main(String[] args){
SeqComplement.sequence = "ATCG";
SeqComplement ob = new SeqComplement();
System.out.println(ob.Complement(ob.sequence));
}
}

此代码给出的结果为 NNNN

我已经尝试过使用 String.concat() 方法,但它没有给我任何结果。

最佳答案

要将字符串转换为字符数组,您应该使用以下代码:

char[] raw = sequence.toCharArray();
char[] complement = sequence.toCharArray();

此外,为了比较字符串,您不应该使用==运算符,您应该在字符串上调用.equals方法。

另一个好的建议是使用 HashMap 来存储补集,如下所示:

HashMap<Character, Character> complements = new HashMap<>();
complements.put('A', 'T');
complements.put('T', 'A');
complements.put('C', 'G');
complements.put('G', 'C');

并像这样补充每个字符:

for (int i = 0; i < raw.length; ++i) {
complement[i] = complements.get(raw[i]);
}

完整代码:

public class SeqComplement {
private static HashMap<Character, Character> complements = new HashMap<>();
static {
complements.put('A', 'T');
complements.put('T', 'A');
complements.put('C', 'G');
complements.put('G', 'C');
}

public String makeComplement(String input) {
char[] inputArray = input.toCharArray();
char[] output = new char[inputArray.length];

for (int i = 0; i < inputArray.length; ++i) {
if (complements.containsKey(inputArray[i]) {
output[i] = SeqComplement.complements.get(inputArray[i]);
} else {
output[i] = 'N';
}
}

return String.valueOf(output);
}


public static void main(String[] args) {
System.out.println(new SeqComplement().makeComplement("AATCGTAGC"));
}
}

关于Java 使用数组连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20283903/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com