How to count the number of commas in a given string in Java

In this tutorial, we will learn how to count the number of commas in the given string in Java.
Now we know that in Java, a string is a combination of alphabets, numbers, special character(like “,” “.” “@” “=” “+” etc.,) alpha-numerics etc., therefore a user can declare any combination of strings in Java
A string is a user-defined combination of the above-mentioned types whereas a character in Java is only a single character i.e user can provide only single character at a time.
Here we want to count the number of commas in a string in Java
Let us understand through a simple example:
let a String s =”one,two,three,alphabet,123@gmail,.com,+code”
we can easily count the number of commas in the given above string.
The number of commas in the above string is: six
Hence we counted the number of commas and we are declaring them. Similarly, this can be achieved in Java as well.
Let us understand it through a Java program:

Java program to count the number of commas in String:

public class Main
{
 public static void main(String args[])
  {
   String s = "one,two,three,alphabet,123@gmail,.com,+code";//user can give any combination
   int commas = 0;
   for(int i=0;i<s.length();i++)
   {
     if(s.charAt(i)==',') 
    {
     commas++;
   }
   System.out.println(s + "has" + commas + "commas");
   }
}
}
output:
       one,two,three,alphabet,123@gmail,.com, code has 6 commas

So here we have declared seven strings which are separated by six commas and in order to print the output we have used iteration method i.e., we used “for loop” this for loop helps the user to iterate the values until the user get desired output and we have declared an “if” condition checks whether the given conditions are true or false.
Here “s.length” helps the user to get the number of commas in the given string
Here “s.charAt” will count the number of commas in the above-mentioned program.
Note: Here counting the number of characters can be done in the following ways: iteration, split method, replace the keyword, match the keyword.
Iteration is the most commonly used method to find the number of characters in a string in Java.

Leave a Reply