Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count uppercase and lowercase letters in a string?

yo, so im trying to make a program that can take string input from the user for instance: "ONCE UPON a time" and then report back how many upper and lowercase letters the string contains:

output example: the string has 8 uppercase letters the string has 5 lowercase letters, and im supposed to use string class not arrays, any tips on how to get started on this one? thanks in advance, here is what I have done so far :D!

import java.util.Scanner;
public class q36{
    public static void main(String args[]){

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Give a string ");
        String input=keyboard.nextLine();

        int lengde = input.length();
        System.out.println("String: " + input + "\t " + "lengde:"+ lengde);

        for(int i=0; i<lengde;i++) {
            if(Character.isUpperCase(CharAt(i))){

            }
        }
    }
}
like image 790
yyzzer1234 Avatar asked Aug 10 '14 02:08

yyzzer1234


3 Answers

Simply create counters that increment when a lowercase or uppercase letter is found, like so:

for (int k = 0; k < input.length(); k++) {
    /**
     * The methods isUpperCase(char ch) and isLowerCase(char ch) of the Character
     * class are static so we use the Class.method() format; the charAt(int index)
     * method of the String class is an instance method, so the instance, which,
     * in this case, is the variable `input`, needs to be used to call the method.
     **/
    // Check for uppercase letters.
    if (Character.isUpperCase(input.charAt(k))) upperCase++;

    // Check for lowercase letters.
    if (Character.isLowerCase(input.charAt(k))) lowerCase++;
}

System.out.printf("There are %d uppercase letters and %d lowercase letters.",upperCase,lowerCase);
like image 179
TNT Avatar answered Oct 20 '22 14:10

TNT


java 8

private static long countUpperCase(String inputString) {
        return inputString.chars().filter((s)->Character.isUpperCase(s)).count();
    }

    private static long countLowerCase(String inputString) {
        return inputString.chars().filter((s)->Character.isLowerCase(s)).count();
    }
like image 44
Niraj Sonawane Avatar answered Oct 20 '22 13:10

Niraj Sonawane


The solution in Java8:

private static long countUpperCase(String s) {
    return s.codePoints().filter(c-> c>='A' && c<='Z').count();
}

private static long countLowerCase(String s) {
    return s.codePoints().filter(c-> c>='a' && c<='z').count();
}
like image 4
Rodolfo Martins Avatar answered Oct 20 '22 13:10

Rodolfo Martins