简体   繁体   中英

counting token occurrances in String with scanner

I have written this method countToken that takes a Scanner s and a String t as parameters, and returns an int. It returns the number of time that t occurs as a token in s. This is as far as I can go and to me it makes sense but it doesnt work right.

public static int countToken(Scanner s, String t)
{
    int count = 0;

    while (s.hasNext()==true)
    {
        if (s.next()==t)
        {
            count++;
        }
    }
    return count;
}

So this is a way I figured after reading all comments and suggestions. Let me know what you think

public static int countToken(Scanner s, String t)
{
    int count=0;
    String token="";
    while (s.hasNext())
    {
        token = s.next();

        if(token.equals(t))
        {
        count++;
        }
        else
        {
        }
    }
    return count;
}

Try this :

countToken(new Scanner("The book is the give the"), "the");

here Scanner contains "The book is the give the" and token t is "the" . so we have to count how many "the" occurs in the Scanner s "The book is the give the" .

public static int countToken(Scanner s, String t)
    {
        int count = 0;

        while (s.hasNext())
        {
            String word=s.next();
            if (word.toLowerCase().equals(t.toLowerCase()))
            {
                count++;
            }
        }
        return count;
    }

output : 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM