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:

  1. Input a string (str).
  2. Run a loop from 0 to str.length().
    1. Read the character at position ‘i’ using str.charAt(i) as ch.
    2. Check if(ch!=’ ‘), If so then increment counter (c++).
  3. Print c.

Here is the Java program that implements the above steps:

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

Leave a Reply

1 + 18 =