Q:

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

belongs to collection: Java String Programs

0

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.

All Answers

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

CountPunctuation.java

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) == ':')   
{    
count++;    
}    
}    
System.out.println("The number of punctuations exists in the string is: " +count);    
}    
}    

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.

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 vowels a... >>
<< Java Program to count the total number of characte...