ehls39119
ehls39119

Reputation: 21

how to iterate over specific elements in string objects (arraylist Java)

ArrayList<String> dnaArray = new ArrayList<>();
ArrayList<Character> compArray = new ArrayList<Character>();

// [tac, tat, tta, aaa, aac, aca, aac, ttt]

public void createCompliment() {
    for (String letters : dnaArray) {
        for (int i = 0, len = letters.length(); i < len; i++) {
            char character = letters.charAt(i);
            if (character == 'a'){
                character = 't';
            } else if (character == 'c') {
                character = 'g';
            }
            compArray.add(character);
        }
    }
}

How would I access specific characters, change 'a' to 't' and similarily from 'c' to 'g'. Then added to a new arraylist and return something like:

[ttg, ttt, ttt, ttt, ttg, tgt, ttg, ttt]

instead of: [t, t, g, t, t, t, t, t, t, t, t, t, t, t, g, t, g, t, t, t, g, t, t, t]

appreciate it

Upvotes: 0

Views: 53

Answers (2)

H&#252;lya
H&#252;lya

Reputation: 3433

You can use a StringBuilder() to create the new String then add it to compArray.

Try this:

for(String letters : dnaArray) {
    StringBuilder sb = new StringBuilder();
    for(int i=0; i<letters.length(); i++) {
        char character = letters.charAt(i);
        if (character == 'a'){
            sb.append("t");
        }
        else if (character == 'c'){
            sb.append("g");
        } else {
            sb.append(String.valueOf(character));
        }
    }
    compArray.add(sb.toString());
}

Output:

[ttg, ttt, ttt, ttt, ttg, tgt, ttg, ttt]

Upvotes: 1

Carlo Moretti
Carlo Moretti

Reputation: 2250

the easiest way in my opinion is to use string replace:

ArrayList<String> dnaArray = new ArrayList<>();
ArrayList<String> compArray = new ArrayList<String>();

public void createCompliment() {
    for (String letters : dnaArray) {
        compArray.add(letters.replace('a', 't').replace('c', 'g'));
    }
}

Upvotes: 1

Related Questions