In this problem, we need to write a java program to count the number of characters in a String.

The input string can also include blank space which is definitely not any type of character, hence we do need to count those.

Steps to Count Characters in a String in Java

  1. Take input a string (str).
  2. Run a loop from 0 to str.length().
  3. Read the character at position ‘i’ using str.charAt(i) into (ch).
  4. If (ch) blank space then increment counter (c++).
  5. Print the value of (c) after loop ends.

Count characters in a String or Sentence in Java

Note: To take sentence as input use nextLine() instead of next().


If you have any suggestion then comment below.

Leave a Reply