java

Java – Count the Total Number of Characters in a String

In this tutorial, we are going to see how to count the total number of characters in a string in Java.

In the example below, we need to count the total number of characters present in the string: “Welcome to StackHowTo!”.

To count the total number of characters present in the string, we will iterate over the string and count the characters. In the above string, the total number of characters present in the string is 22.
 

 

How to Count the Total Number of Characters in a String in Java
public class Main  
{  
    public static void main(String[] args) {  
        String text = "Welcome to StackHowTo!";  
        int count = 0;  
          
        //Count every character except space
        for(int i = 0; i < text.length(); i++) {  
            if(text.charAt(i) != ' ')  
                count++;  
        }  

        System.out.println("Total number of characters is: " + count);  
    }  
}

Output:

Total number of characters is: 20
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *