1. Using charAt() method
2. Using replaceAll() method
Read Also: How to capitalize first letter of a string in Java
Before moving forward with the solution, first, we will understand the question with the help of examples.
"Alive, is, awesome" // 2 commas "23, 34, 45, 56, 67, 78, 89, 100" // 7 commas
Java Program to Count Number of Commas in a String
1. Using charAt() method
public class FindNumberOfCommas { public static void main(String args[]) { int count = 0; String givenString = "Alive, is , Awesome"; for( int i= 0; i < givenString.length(); i++) { if(givenString.charAt(i) == ',') count++; } System.out.println("Given String has "+ count + " commas"); } }
Output:
Given String has 2 commas
Algorithm
1. Iterate each character of the givenString using the charAt() method2. Check if condition in the loop
3. if true then increase the count by 1, otherwise continue the for loop
4. Print the number of commas in the givenString
2. Using replaceAll() method
public class FindNumberOfCommas2 { public static void main(String args[]) { String givenString = "Be, in , Present"; int count = givenString.replaceAll("[^,]","").length(); System.out.println("Given String has "+ count + " commas"); } }
Output:
Given String has 2 commas
Algorithm
1. Call the replaceAll() method on the givenString.2. We are using regex "[^,]" in the replaceAll method.
3. givenString.replaceAll("[^,]","").length() means replace all the characters that are not comma with empty String. It will leave us with the "," only String. We are calling the length() of the "," String, which will give us the number of commas in the givenString.
That's all for today, please mention in comments in case you have any questions related to count number of commas in a string in Java.