Java program to count the total number of punctuation characters exists in a string

Configurare noua (How To)

Situatie

We are going to create a Java program that counts the total number of punctuations in a given string.

Solutie

Pasi de urmat

public class CountPunctuation
{
public static void main (String args[])
{
//Stores the count of punctuation marks
int count = 0;
String str = “Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras odio turpis, accumsan in pharetra sit amet, dictum quis nisl.”;
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

Tip solutie

Permanent

Voteaza

(1 din 4 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?