How to count the number characters in a Java string?


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

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 20-Feb-2020

565 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements