Bruno Andrade
Bruno Andrade

Reputation: 261

Compare two Strings letter by letter

Well, I have two strings to compare and check letter by letter if they match, and if hits a '-' i need to count how many '-' there's in sequence and put them in a group as if they were only one char and count how many T and C there in this group of '-'. The output should be like 2.1T and 2.2C and the other one 5.2C.

    String dna1 = "TC---CA--";  
    String dna2 = "TCTCCCACC";
    char[] dnaChar = dna1.toCharArray(), dna2Char = dna2.toCharArray();
    int cont = 0;
    int letters = 0;


    for (int i = 0; i < dnaChar.length; i++) {
        if (dnaChar[i] != dna2Char[i]) {
            int mut = i + 1;

            if (dna1.charAt(i) == '-') {

                cont++;
                mut -= cont;
                if (dna2.charAt(i) == 'C') {
                    letters++;
                }

                System.out.println(mut + "." + letters + dna2.charAt(i));
            } else {
                letters = 0;
                cont = 0;
                mut += 1;
                System.out.println("" + dna1.charAt(i) + " " + mut + " " + dna2.charAt(i));
            }
        }
    }

The output 2.0T 2.1C 2.2C 4.3C 4.4C And what i want 2.1T 2.2C 5.2C

Upvotes: 2

Views: 2538

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213411

The output that you expect will never be obtained from your above code.. Because in your if construct will be executed every time you encounter a '-' in your first string.. And hence you will have 5 outputs, not 3..

Second, to get what you need, you will have to do some extra work here..

  • First When you encounter a '-' in your 1st String, you need to store the corresponding character from your second String into some variable.. Because you need it to check for continuous characters.
  • Second, each time to get a '-', check the current character with the last character matched for the previous '-'. If it is the same, increase the count by 1,
  • If it is not the same, just print what you want.. and reset your count to 0
  • As soon as you encounter the character which not '-' in your first string, print the current character and the count value, and reset them..

You can try to code according to the steps I have mentioned..

*PS: - For any problem you get to code, you should first write down the steps you should follow to solve it on paper. Then convert it to code step-by-step. It will be easier to understand the problem and solve it also..

Upvotes: 3

Related Questions