counting the number of times a word is typed in

2019-09-19 11:28发布

问题:

i found a solution similar to my problem here:

import java.util.Scanner;
public class Counter
{
    public static void main ( String args[] )
    {
        String a = "", b = "";
        Scanner s = new Scanner( System.in );

        System.out.println( "Enter a string: " );
        a = s.nextLine();
        while ( b.length() != 1 )
        {
            System.out.println( "Enter a single character: " );
            b = s.next();
        }

        int counter = 0;
        for ( int i = 0; i < a.length(); i++ )
        {
            if ( b.equals(a.charAt( i ) +"") )
                counter++;
        }
        System.out.println( "Number of occurrences: " + counter );
    }
}

this program only counts the amount of times a selected letter appears. i need to do the same but with an entire word. How would i modify this code to do what I need it to? I'm not the greatest at programming. Your help is greatly appreciated. Thanks!

回答1:

You can use split string

You can split the string on space like

String[] words =a.split(" ");

Then loop through it like

for(String word : words) {
    if(word.equals(testWordToCompare)
        counter++;
    }
}

So your new code would look like :

import java.util.Scanner;
public class Counter
{
    public static void main ( String args[] )
    {
        String a = "", testWordToCompare = "exist";
        Scanner s = new Scanner( System.in );

        System.out.println( "Enter a string: " );
        a = s.nextLine();
        String[] words =a.split(" ");
        int counter = 0;
        for(String word : words) {
           if(word.equals(testWordToCompare)
               counter++;
           }
        }
        System.out.println( "Number of occurrences of " + testWordToCompare +" is : " + counter );
    }
}