Search code examples
javasplitcontains

printing parts of string that contains av in java


I´m trying to take Strings of input and print out the words that contain "av"

Here is my code:

        while (true) {
        String jono = lukija.nextLine();
        String[] loydaAvSana = jono.split(" ");

        if (jono.isEmpty()) {
            System.out.println("loppu");
            break;

        }

        if(jono.contains("av")){
            for(int i = 0; i < loydaAvSana.length; i++){
                System.out.println(loydaAvSana[i]);
            }
        }

for example, if I write: Hello World It shouldn't do anything, but when I write for example

"avaava ovi ava"

it should print:

avaava

ava

So it should get the Strings that contain "av"

I know that I should use split method and also contains method but I don't know how to print only the strings that contain "av"

My codes output is like this:

Hello world
ava ovi ava
ava
ovi
ava

Solution

  • while (true) {
        String jono = lukija.nextLine();
        if (jono.isEmpty()) {
            System.out.println("loppu");
            break;
        }
    
        if(jono.contains("av")){
            String[] loydaAvSana = jono.split(" ");
            for(int i = 0; i < loydaAvSana.length; i++){
                if (loydaAvSana[i].contains("av") {
                    System.out.println(loydaAvSana[i]);
                }
            }
        }
    }
    
    • Read the next line.
    • If it's empty, exit the loop.
    • Otherwise, check if it conatins "av".
    • If it does, split it into words.
    • Iterate through all the words.
    • If a word contains "av", print that word.