Q:

Java Program to count the total number of characters in a string

belongs to collection: Java String Programs

0

In this program, we need to count the number of characters present in the string:

The best of both worlds

To count the number of characters present in the string, we will iterate through the string and count the characters. In above example, total numbers of characters present in the string are 19.

For programming, follow the algorithm given below:

Algorithm

  • STEP 1: START
  • STEP 2: DEFINE String string = "The best of both worlds".
  • STEP 3: SET count =0.
  • STEP 4: SET i=0. REPEAT STEP 5 to STEP 6 UNTIL i<string.length
  • STEP 5: IF (string.charAt(i)!= ' ') then count =count +1.
  • STEP 6: i=i+1
  • STEP 7: PRINT count.
  • STEP 8: END

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

public class CountCharacter    
{    
    public static void main(String[] args) {    
        String string = "The best of both worlds";    
        int count = 0;    
            
        //Counts each character except space    
        for(int i = 0; i < string.length(); i++) {    
            if(string.charAt(i) != ' ')    
                count++;    
        }    
            
        //Displays the total number of characters present in the given string    
        System.out.println("Total number of characters in a string: " + count);    
    }    
}     

Output:

Total number of characters in a string: 19

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java Program to Count the Total Number of Punctuat... >>