counting the number of times a word is typed in

六月ゝ 毕业季﹏ 提交于 2019-12-13 08:36:48

问题


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 );
    }
}


来源:https://stackoverflow.com/questions/25939674/counting-the-number-of-times-a-word-is-typed-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!