Java Program to Count the Total Number of Punctuation Characters Exists in a String

In the previous Java string programs, we have counted the number of words, white spaces, vowels, consonants, and characters. Sometimes it also becomes necessary to count the total number of punctuations in a string. So, in this section, we are going to create a Java program that counts the total number of punctuations in a given string.

Steps to Count the Punctuations

  1. Define a string or read from the user.
  2. Declare a variable to count the number of punctuations and initialized it with 0.
  3. Now, match each and every character with the punctuation marks (!, . , ‘ , – , ” , ? , ; ). If any character in the string is matched with any of the punctuation marks, increment the count variable by 1.
  4. At last, print the count variable that gives the total number of punctuations.

Let’s implement the above steps in a Java program.

CountPunctuation.java

  1. public class CountPunctuation   
  2. {    
  3. public static void main (String args[])   
  4. {    
  5. //Stores the count of punctuation marks    
  6. int count = 0;    
  7. String str = “He said, ‘The mailman loves you.’ I heard it with my own ears.”;    
  8. for (int i = 0; i < str.length(); i++)   
  9. {    
  10. //Checks whether given character is punctuation mark    
  11. if(str.charAt(i) == ‘!’ || str.charAt(i) == ‘,’ || str.charAt(i) == ‘;’ || str.charAt(i) == ‘.’ ||  str.charAt(i) == ‘?’ || str.charAt(i) == ‘-‘ ||    
  12. str.charAt(i) == ‘\” || str.charAt(i) == ‘\”‘ || str.charAt(i) == ‘:’)   
  13. {    
  14. count++;    
  15. }    
  16. }    
  17. System.out.println(“The number of punctuations exists in the string is: ” +count);    
  18. }    
  19. }    

Output:

The number of punctuations exists in the string is: 5

In the above program, we have used a for loop that iterates over the string and executes till the length of the string. For determining the position of the characters in a string, we have used the charAt() method that returns the character at the specified index in a string. For each iteration, each and every character is matched with the punctuation marks by using the == operator. If any character is matched with a punctuation mark the count variable is incremented by 1. At last, we have printed the value of the count variable.

Leave a Comment