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
- Define a string or read from the user.
- Declare a variable to count the number of punctuations and initialized it with 0.
- 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.
- At last, print the count variable that gives the total number of punctuations.
Let’s implement the above steps in a Java program.
- public class CountPunctuation
- public static void main (String args)
- //Stores the count of punctuation marks
- int count = 0;
- String str = “He said, ‘The mailman loves you.’ I heard it with my own ears.”;
- for (int i = 0; i < str.length(); i++)
- //Checks whether given character is punctuation mark
- if(str.charAt(i) == ‘!’ || str.charAt(i) == ‘,’ || str.charAt(i) == ‘;’ || str.charAt(i) == ‘.’ || str.charAt(i) == ‘?’ || str.charAt(i) == ‘-‘ ||
- str.charAt(i) == ‘\” || str.charAt(i) == ‘\”‘ || str.charAt(i) == ‘:’)
- System.out.println(“The number of punctuations exists in the string is: ” +count);
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.