How to count the number characters in a Java string?

Java 8Object Oriented ProgrammingProgramming

Declare an integer, initialize it with 0, in for loop increment it for each character.

Example

Live Demo

public class Sample {
   public static void main(String args[]) {

      String str = new String("Hi welcome to Tutorialspoint");
      int count = 0;
      for(int i = 0; i<str.length(); i++) {
         count++;
      }
      System.out.println("Number characters in the given string (including spaces) "+count);
   }
}

Output

Number characters in the given string (including spaces) 28
raja
Published on 10-Jan-2018 10:39:49
Advertisements