java
Parameters: String str
str is the string in which the consonants are to be counted.
Returns: The total number of consonants present in the given string
This java function takes a string as input and counts the number of consonants. The consonants in english language are: {b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z}.
Welcome to this blog post. As a programmer, you are about to learn something new and engaging. This post will elucidate with clarity and precision on how to create a function in java to count the consonants in a string. No unnecessary jargon, just pure programming. Understand that your involvement is not passive, we are going to construct this together. Let's get started.
The first step is to set up our method that takes a string as input. Inside this method, we're going to set up a string of all the consonants in the English language since we're going to be searching for these in our string. Both lower and upper case are considered.
public static int countConsonants(String str) {
String consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
}
Next, we need to initialize a counter that will keep track of how many consonants were found.
int count = 0;
Now we need to loop through each character in the string. If that character is a consonant (according to our string of consonants), we will increment our counter.
for (int i = 0; i < str.length(); i++) {
if (consonants.contains(String.valueOf(str.charAt(i)))) {
count++;
}
After our loop runs, it's time to return our counter. This will represent the number of consonants in the string.
return count;
Finally, let's combine all these steps to see the complete code implementation.
public static int countConsonants(String str) {
String consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (consonants.contains(String.valueOf(str.charAt(i)))) {
count++;
}
}
return count;
}
That's all there is to it! With this method, you can count the number of consonants in any English language string.
The function uses the principle of incremental counting. It iterates through the string, checks whether each character is a consonant using a predefined list of consonants, and increments a counter if it is.
Learn more