Java Programs

Java Program to Find the characters count in String

Here we are going to write a program to find the characters count in String using Java.

Find the characters count in String :

[java]

import java.util.Scanner;

public class StringCharcterCountExample {

    public static void main(String a[]) throws Exception {

        int count = 0;
        System.out.println("Enter a String");
        Scanner s1 = new Scanner(System.in);
        String inputValue = s1.nextLine();
        System.out.println("Enter a charcter to count");
        char c = (char) System.in.read();

        if (inputValue != null && !inputValue.equals("")) {

            char[] ch1 = inputValue.toCharArray();
            for (int i = 0; i < ch1.length; i++) {

                if (ch1[i] == c) {
                    count++;
                }
            }
            System.out.println("The ‘"+c+"’ is available in "+
                     count+" times.");
        }
    }
}
[/java]

Output :

Enter a String
onlinetutorialspoint
Enter a charcter to count : t
The 't' is available in 3 times.

Happy Learning :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment