mardi 2 mars 2021

How can I count with indexOf in Java?

I want to replace from String and print how many times it replaced.

for examples)
Input : aabba
from : aa
to : bb
ddbba
replaced : 1

Input : AAccaabbaaaaatt
from : aa
to : bb
ddccddbbddddatt
replaced : 4

I have a problem here:

for (int i = 0; i < input.length(); i++) {
        if (inputL.indexOf(curStrL, i) > -1) {
            cnt++;
            i = (inputL.indexOf(curStrL, i))+1; // this part!
        } else
            continue; 
    } // for

My teacher said just use .indexOf and .replace, and .toLowerCase.

She gave some examples and they always replace two letters to two letters. That's the reason why I put '+1' to find another letter. If I remove that '+1', it counts 'aaa' twice.(aa a and a aa. And it replaced to 'dda', so it's wrong.) But this time when I replace only one letter(ex.a), it counts less numbers than actually it has to be.(ex.'aaa' counts just two times.)

With the examples from teacher, it works well cuz all of them replace two letters. But I want to improve this.

Here is all of my code:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    while (true) {
        System.out.print("Input : ");
        String input = scan.next();
        System.out.print("from : ");
        String curStr = scan.next();
        System.out.print("to : ");
        String chStr = scan.next();

        String inputL = input.toLowerCase();
        String curStrL = curStr.toLowerCase();
        String chStrL = chStr.toLowerCase();

        String output = inputL.replace(curStrL, chStrL);

        int cnt = 0;
        if (inputL.indexOf(curStrL) == -1) {
            System.out.println("Do it again");
        } else
            System.out.println(output);

    for (int i = 0; i < input.length(); i++) {
        if (inputL.indexOf(curStrL, i) > -1) {
            cnt++;
            i = (inputL.indexOf(curStrL, i))+1; 
            // *** to make the code find from the next letter! ***
        } else
            continue; 
    } // for

        if (cnt > 0)
            System.out.println("replaced : " + cnt);
        else
            {System.out.println("can't replace. Do it again");
            break;}

        System.out.println("----------------");

    } // while
} // main

Aucun commentaire:

Enregistrer un commentaire