Search code examples
javacountcpu-worduppercase

How do I count the words that start with an uppercase letter in java?


I want to make a program that prints the number of words that START with an uppercase letter. So I made two strings str1 = "The deed is done" and str2 = "My name is Bond, JAMES Bond". For the first string, it printed 1 which is what I wanted. But for the second one it prints 8 instead of 4 because JAMES is capitalized.


    public static void main(String[] args){
        String str1 = "The deed is done";
        String str2 = "My name is Bond, JAMES Bond";

        System.out.println(uppercase(str2));
    }

    public static int uppercase(String str){
        int cnt = 0;

        for(int i = 0; i < str.length(); i++){
            if(Character.isUpperCase(str.charAt(i)))
                cnt++;
        }

        return cnt;
    }

That's what I have so far. How would I make it so that the other letters in that word aren't counted?


Solution

  • You should check the first character of each word in the input string, instead of all characters of the input string.

    public static int uppercase(String str){
        int cnt = 0;
    
        String[] words = str.split(" ");
    
        for(int i = 0; i < words.length; i++){
            if(Character.isUpperCase(words[i].charAt(0)))
                cnt++;
        }
    
        return cnt;
    }
    

    A more 'declarative approach' could use a Stream

    public static long uppercase2(String str){
        return Arrays.stream(str.split(" "))
                .map(word -> word.charAt(0))
                .filter(Character::isUpperCase)
                .count();
    }