Problem: Write a Java program to count the number of characters in a given string.
The input string can also have white space which is definitely not a character, so we don’t need to count them.
Steps to count characters of a String in Java:
- Input a string (str).
- Run a loop from 0 to str.length().
- Read the character at position ‘i’ using str.charAt(i) as ch.
- Check if(ch!=’ ‘), If so then increment counter (c++).
- Print c.
Here is the Java program that implements the above steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import java.util.Scanner; public class CountCharacters { public static void main(String args[]){ Scanner in = new Scanner(System.in); String str; //To store string char ch; //To store a single character int c=0; //counter //input string System.out.println("Enter a String/Sentence"); str = in.nextLine(); //Loop through each character for(int i=0; i<str.length(); i++){ //Read character at 'i' ch = str.charAt(i); //check if the character is not blank space, //if so then increment 'c' if(ch != ' ') c++; } //ouput counter System.out.println("Total characters: "+c); } } |
Note: Use nextLine() instead of next() for sentence as the input.
Output:
Enter a String/Sentence
pencil programmer
Total characters: 16
Enter a String/Sentence
pencil programmer
Total characters: 16