Trying to add a character before each vowel in a String - java

I want to insert an "ab" before every vowel in a word
Example, if the user enters the word: fire
it has to be changed to: fabirabe
but my code is only entering the ab before the word like: abfire. How can I fix that?
Here's my code so far:
import java.util.Scanner;
public class Foothill
{
// class variables shared by more than one method
String prompt;
static String strUserResponse;
// main method
public static void main (String[] args)
{
giveInstructions();
getUserInput();
convertToTurkeyIrish();
vowelCounter();
}
public static String convertToTurkeyIrish()
{
String turkeyIrish = strUserResponse;
String turkeyIrish2;
turkeyIrish2 = "ab" + strUserResponse.replaceAll("(aeiouAEIOU)", "$1ab");
System.out.println("Word In Turkey Irish: " + turkeyIrish2);
return turkeyIrish;
}
public static void vowelCounter()
{
int vowel = 0;
strUserResponse.length();
char vowels;
vowels = ' ';
for (int j = 0; j <= strUserResponse.length() - 1 ; j++)
{
vowels = strUserResponse.charAt(j);
if ((vowels == 'a') || (vowels == 'A') || (vowels == 'e') || (vowel == 'E') || (vowel == 'i')|| (vowels == 'I') || (vowels == 'o') (vowels == 'O') || (vowel == 'u') || (vowels == 'u'))
{
System.out.println("Vowels in " + strUserResponse + ": " + vowel++);
}
}
}
}

Your regex is wrong, and so is the replace string. Try this:
strUserResponse.replaceAll("([aeiouAEIOU])", "ab$1");

Change your regex to:
(?i)(a|e|i|o|u)
and the replacement to:
ab$1
Your current regex is aeiouAEIOU which matches a sequence of characters: "aeiouAEIOU".
Test it:
System.out.println("fire".replaceAll("(?i)(a|e|i|o|u)", "ab$1"));
// fabirabe
Or as suggested by #amit, you can simply use a character class and write [aeiou]. Note that I used the (?i) to indicate that the regex should be case insensitive.

Related

Removing recurring vowels in a string

this is the program can anyone help me
at first i have given the string first part is working fine it finds the vowels in string and it prints
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "History can also refer to the academic discipline ";
int count = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'u'
|| a.charAt(i) == 'u') {
System.out.println("The sentence have vowels:" + a.charAt(i));
count++;//counting the number of vowels
}
if (a.charAt(i+1) == 'a' || a.charAt(i+1) == 'e' || a.charAt(i+1) == 'i' || a.charAt(i+1) == 'u'
|| a.charAt(i+1) == 'u') {i++;}//finding reoccurring vowels
}
System.out.println("number of vowels:" + count);
}
}
in second part im trying to skip the reoccurring vowels but its not working
You need to make a couple of changes:
Run the loop till a.length() - 1 as you are already checking for i+1st character inside the loop
Reset the count if the second if condition is not satisfied.
e.g.:
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "History can also refer to the academic discipline ";
int count = 0;
for (int i = 0; i < a.length() - 1; i++) {
if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'u'
|| a.charAt(i) == 'u') {
System.out.println("The sentence have vowels:" + a.charAt(i));
count++;//counting the number of vowels
}
//finding reoccurring vowels
if (a.charAt(i+1) == 'a' || a.charAt(i+1) == 'e' || a.charAt(i+1) == 'i' || a.charAt(i+1) == 'u'
|| a.charAt(i+1) == 'u') {
i++;
} else{
count = 0;
}
}
System.out.println("number of vowels:" + count);
}
How about this
public static void main(String[] args) {
String a = "History can also refer to the academic discipline ";
int count = 0;
boolean lastWasVowel = false;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'o'
|| a.charAt(i) == 'u') {
if(!lastWasVowel) {
count++;
}
lastWasVowel = true;
} else {
lastWasVowel = false;
}
}
System.out.println("number of vowels:" + count);
}

Java: How do I return user to main menu if user input is not a single alphabetic lowercase letter?

I'm trying to run a program that will allow the user to input both a char keyCharacter and a String theString. Then, using these inputs, I will mask the keyCharacter if it occurs in theString with a "$", remove the keyCharacter from the theString, and finally, count the number of times the keyCharacter occurs in theString altogether.
Every method is working fine, except the method getKeyCharacter where the user has to input a char:
The user can only enter a single letter (e.g. q, or z).
If the user enters anything other than that single letter (which can be anything from a word, phrase, sentence, special character like # or $, blank space or tabs, or just pressing enter), then the program returns the user to the original question that asks for the keyCharacter from the user. This should continue looping back to that original question until the user enters a valid input.
Since I'm still a beginner to java and loops are my weakness so far, this part is causing me a lot of trouble. I know I should be using a while loop, it is the logic behind the nested loops that is really confusing me.
From searching for possible solutions, I know there are these things called regex and try-catch exception that could help with my issue, but since we haven't gone over that explicitly in class, I'd prefer not to deal with that for now. Thank you.
Here's a paste of my code:
import java.util.*;
public class Foothill {
// main method
public static void main (String[] args) {
char keyCharacter = getKeyCharacter();
String theString = getString();
maskCharacter(theString, keyCharacter);
countKey(theString, keyCharacter);
removeCharacter(theString, keyCharacter);
}
// get keyCharacter
public static char getKeyCharacter() {
Scanner inputStream = new Scanner(System.in);
boolean stop = false;
String firstPrompt, strKeyCharacter;
char keyCharacter = ' ';
while (stop != true) {
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.print(firstPrompt);
strKeyCharacter = inputStream.nextLine();
while (strKeyCharacter.length() != 1) {
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.print(firstPrompt);
strKeyCharacter = inputStream.nextLine();
}
keyCharacter = strKeyCharacter.charAt(0);
while (strKeyCharacter.length() == 1) {
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.print(firstPrompt);
strKeyCharacter = inputStream.nextLine();
if (keyCharacter == 'a' || keyCharacter == 'b' || keyCharacter == 'c' || keyCharacter == 'd'
|| keyCharacter == 'e' || keyCharacter == 'f' || keyCharacter == 'g' || keyCharacter == 'h'
|| keyCharacter == 'i' || keyCharacter == 'j' || keyCharacter == 'k' || keyCharacter == 'l'
|| keyCharacter == 'm' || keyCharacter == 'n' || keyCharacter == 'o' || keyCharacter == 'p'
|| keyCharacter == 'q' || keyCharacter == 'r' || keyCharacter == 's' || keyCharacter == 't'
|| keyCharacter == 'u' || keyCharacter == 'v' || keyCharacter == 'w' || keyCharacter == 'x'
|| keyCharacter == 'y' || keyCharacter == 'z') {
System.out.println("You entered: " + keyCharacter + '\n');
stop = true;
} else {
break;
}
}
}
return keyCharacter;
}
// declare final = 4 to be constant
public static final int minimumLength = 4;
// get theString
public static String getString() {
Scanner inputStream = new Scanner(System.in);
String secondPrompt, theString;
do {
secondPrompt = "Please enter a phrase or sentence >= 4: ";
System.out.print(secondPrompt);
theString = inputStream.nextLine();
System.out.print('\n');
} while (theString.length() < minimumLength || theString == null || theString.length() == 0);
inputStream.close();
return theString;
}
// mask keyCharacter with $
public static String maskCharacter(String theString, char keyCharacter) {
theString = theString.replace(keyCharacter, '$');
System.out.println("String with " + " '" + keyCharacter + "' " + " masked.");
System.out.println(theString + '\n');
return theString;
}
// count number of times keyCharacter occurs in theString
public static void countKey(String theString, char keyCharacter) {
int countChar = 0;
for (int charTimes = 0; charTimes < theString.length(); charTimes++) {
if (theString.charAt(charTimes) == keyCharacter) {
countChar++;
}
}
System.out.println( "The key character occurs " + countChar + " times. \n");
return;
}
// remove keyCharacter from theString
public static void removeCharacter(String theString, char keyCharacter) {
theString = theString.replace(String.valueOf(keyCharacter), "");
System.out.println("String with " + "'" + keyCharacter + "' removed: ");
System.out.println(theString);
return;
}
}
And here's a paste of my run (as you can see, there is some serious debugging to be done in my program):
Please enter a SINGLE character to act as key: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key: f
You entered: f
Please enter a SINGLE character to act as key:
// which then continues so on so forth...
public static char getKeyCharacter(){
Scanner inputStream = new Scanner(System.in);
boolean stop = false;
String firstPrompt, strKeyCharacter;
char keyCharacter = ' ';
while(!stop){
firstPrompt = "Please enter a SINGLE character to act as key: ";
System.out.println(firstPrompt);
strKeyCharacter = inputStream.nextLine();
//check if the input contains only 1 character
boolean isSingleChar = (strKeyCharacter.length() == 1);
//check if the input character is within the ASCII code of 97 (a) to 122 (z)
boolean isValidChar =
strKeyCharacter.charAt(0) >= 97 &&
strKeyCharacter.charAt(0) <= 122;
if(isSingleChar && isValidChar){
keyCharacter = strKeyCharacter.charAt(0);
stop = true;
}
}
return keyCharacter;
}

How to turn a user given String into Pig Latin?

Im trying to turn a string taken from the user into Pig Latin. I cannot use any special classes, methods, or arrays. I can only use a Scanner to create a object to take the string from the user and .length and .charAt, in addition to any type of looping. (Also cannot use switch statements or the break keyword)
Here is an example of what my output is suppose to be:
Enter a line of text: this is a test.
Input : this is a line of text.
Output: his-tay is-way a-way ine-lay of-way ext-tay.
Here is my code, I can only get my code to work with one word and it must have a space at the end. Only one loop works at a time depending on the loop. Im not sure what to do if I get an entire String.
I know that when the user enters a space that signals a new word, and when they enter a period, that signals the ending.
I had a hard time understanding your code. (It looks like you are trying to do it two ways at once?) Regardless, I believe I was able to understand your question. Here is a compilable and runnable example:
import java.util.Scanner;
public class PigLatin
{
public static void main(String[] args)
{
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
if (text != null && text.length() > 0)
{
int i = 0;
// this iterates through the whole string, stopping at a period or
// the end of the string, whichever is closer
while (i < text.length() && text.charAt(i) != '.')
{
// these three variables only exist in this code block,
// so they will be re-initialized to these values
// each time this while loop is executed
char first = '\0'; // don't worry about this, I just use this value as a default initializer
boolean isFirst = true;
boolean firstIsVowel = false;
// each iteration of this while loop should be a word, since it
// stops iterating when a space is encountered
while (i < text.length()
&& text.charAt(i) != ' '
&& text.charAt(i) != '.')
{
// this is the first letter in this word
if (isFirst)
{
first = text.charAt(i);
// deal with words starting in vowels
if (first == 'a' || first == 'A' || first == 'e' || first == 'E'
|| first == 'i' || first == 'I' || first == 'o' || first == 'O'
|| first == 'u' || first == 'U')
{
System.out.print(first);
firstIsVowel = true;
}
// make sure we don't read another character as the first
// character in this word
isFirst = false;
}
else
{
System.out.print(text.charAt(i));
}
i++;
}
if (firstIsVowel)
{
System.out.print("-tay ");
}
else if (first != '\0')
{
System.out.print("-" + first + "ay ");
}
i++;
}
System.out.print('\n'); //for clean otuput
}
}
}
There are a few comments in there that might help guide you through my logic. This is almost definitely not the most efficient way to do this (even with your limitations), as I only whipped it up as a example of the type of logic you could use.
You could break it up into words, then process the current word when you hit a space or period:
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
String curWord = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' || text.charAt(i) == '.') {
if (curWord.charAt(0) == 'a' || curWord.charAt(0) == 'e' ||
curWord.charAt(0) == 'i' || curWord.charAt(0) == 'o' ||
curWord.charAt(0) == 'u') {
System.out.print(curWord + "-way ");
} else {
for (int j = 1; j < curWord.length(); j++) {
System.out.print(curWord.charAt(j);
}
System.out.print("-" + curWord.charAt(0) + "ay ");
//System.out.print(curWord.substring(1)+"-"+curWord.charAt(0)+"ay ");
}
curWord = "";
} else {
curWord += text.charAt(i);
}
}

Java Comparing char values with set char values in a while loop

I need to compare char values with set char values 'g' 'c' 'a' 't'(lower and upper case), for i want only those values to be entered. I can not seem to get certain cases of my input validation working.
f in the below strings can stand for any length of string that is not characters g,c,a,t.
The string "fffffff" keeps in the loop.
The string "fgf" keeps in the loop.
However, i want the strings, "fffffg" or "gfg" to exit the loop, and they are not doing so.
The actual purpose of the exercise, to take a user input of nucleotides like g,c,a,t like the one's in DNA, and convert them into the complementary string of RNA. G is complement to C and vice versa. A is complement to U(the T is replaced with U) and vice versa.
So if the string is "gcat", the response for RNA should be "cgua".
import java.text.DecimalFormat;
import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
import java.util.Random;
//getting my feet wet, 1/13/2015, program is to take a strand of nucleotides, G C A T, for DNA and give
//the complementary RNA strand, C G U A.
public class practiceSixty {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
String input = null;
boolean loopControl = true;
char nucleotide;
while(loopControl == true)
{
input = JOptionPane.showInputDialog(null, " Enter the sequence of nucleotides(G,C,A and T) for DNA, no spaces ");
for(int i = 0; i < input.length(); i++)
{
nucleotide = input.charAt(i);
if(!(nucleotide == 'G' || nucleotide == 'g' || nucleotide == 'C' || nucleotide == 'c' || nucleotide == 'A' || nucleotide == 'a' || nucleotide == 'T' || nucleotide == 't' ))
{
loopControl = true;
}
else if(nucleotide == 'G' || nucleotide == 'g' || nucleotide == 'C' || nucleotide == 'c' || nucleotide == 'A' || nucleotide == 'a' || nucleotide == 'T' || nucleotide == 't' )
{
loopControl = false;
System.out.println(nucleotide);
}
}
}
JOptionPane.showMessageDialog(null, "the data you entered is " + input);
StringBuilder dna = new StringBuilder(input);
for(int i = 0; i < input.length(); i++)
{
nucleotide = input.charAt(i);
if(nucleotide == 'G' || nucleotide == 'g' )
{
dna.setCharAt(i, 'c');
}
else if( nucleotide == 'C' || nucleotide == 'c')
{
dna.setCharAt(i, 'g');
}
if(nucleotide == 'A' || nucleotide == 'a')
{
dna.setCharAt(i, 'u');
}
else if(nucleotide == 'T' || nucleotide == 't')
{
dna.setCharAt(i, 'a');
}
}
JOptionPane.showMessageDialog(null, "the DNA is , " + input + " the RNA is " + dna);
}
});
}
}
You could do your check with a single regular expression, and then just use a do/while loop to keep prompting for input until the user enters something valid.
do {
input = JOptionPane.showInputDialog(
null, " Enter the sequence of nucleotides(G,C,A and T) for DNA, no spaces ");
} while (!input.matches("[GCATgcat]+"));
The regular expression will match any input that consists of one or more letters of the 8 shown. When you don't get a match, the loop repeats.

How can I check how many consonants and vowels there are in a sentence in Java?

At the end of my loop, I am planning on displaying the number of consonants and vowels in the sentence. I was wondering if there was a more efficient way to check how many consonants and vowels are in a given sentence, rather than using an if statement and manually inputting every letter. (key refers to my Scanner which has already been initialized)
Edit: It needs to ignore digits and other special characters, so for example if I write Hello# how 1are you?. There should be 8 vowels and 6 consonants.
System.out.println("Please enter the sentence to analyze: ");
String words = key.nextLine(); //the sentence the user inputs
int c = 0; //# of consonants
int v = 0; //# of vowels
int length = words.length(); //length of sentence
int check; //goes over each letter in our sentence
for(check = 0; check < length; check++){
char a = words.charAt(check);
if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o'
|| a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y')
v = v + 1;
else if(a == 'b' || a == 'B' || a == 'c' || a == 'C' || a == 'd' || a == 'D' || a == 'f'
|| a == 'F' || a == 'g' || a == 'G' || a == 'h' || a == 'H' || a == 'j' || a == 'J'
|| a == 'k' || a == 'K' || a == 'l' || a == 'L' || a == 'm' || a == 'M' || a == 'n'
|| a == 'N' || a == 'p' || a == 'P' || a == 'q' || a == 'Q' || a == 'r' || a == 'r'
|| a == 's' || a == 'S' || a == 't' || a == 'T' || a == 'v' || a == 'V' || a == 'w'
|| a == 'W' || a == 'x' || a == 'X' || a == 'z' || a == 'Z')
c = c + 1;
}
Use Character.isLetter(ch) to determine if the character is a vowel or a consonant, then check to see if the character in question is in the set of vowels.
One way to create the set of vowels:
Set<Character> vowels = new HashSet<Character>();
for (char ch : "aeiou".toCharArray()) {
vowels.add(ch);
}
And to increment v or c:
if (Character.isLetter(a)) {
if (vowels.contains(Character.toLowerCase(a))) {
v++;
} else {
c++;
}
}
Assuming you already have a letter (vowel or consonant, not a digit nor a symbol or anything else), then you can easily create a method to define if the letter is a vowel:
static final char[] vowels = { 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'y', 'Y' };
public static boolean isVowel(char c) {
for (char vowel : vowels) {
if (c == vowel) {
return true;
}
}
return false;
}
public static boolean isConsonant(char c) {
return !isVowel(c);
}
Note that I set Y and y as vowels since seems that they are in your language. In Spanish and English, Y is a consonant (AFAIK).
You can easily check if the char is a letter or not using Character#isLetter.
So, your code would become into:
for(check = 0; check < length; check++){
char a = words.charAt(check);
if (Character.isLetter(a)) {
if (isVowel(a)) {
v++;
} else {
c++;
}
}
}
How about something like
String vowels = "aeiouyAEIOUY"; // you can declare it somewhere before loop to
// to avoid redeclaring it each time in loop
//inside loop
if ((a>='a' && a<='z') || (a>='A' && a<='Z')){ //is letter
if (vowels.indexOf(a)!=-1) //is vowel
v++;
else //is consonant
c++;
}
I am sure this can be improved upon, but I'll throw it in the ring anyways.
Remove non-characters from the sentence, lowercase it, then convert to a char array and compare it to a char array of vowels that are all lowercase.
String myText = "This is a sentence.";
int v = 0;
char[] vowels = {'a','e','i','o','u'};
char[] sentence = myText.replaceAll("[^a-zA-Z]","").toLowerCase().toCharArray();
for (char letter : sentence) {
for (char vowel : vowels) {
if (letter == vowel) {
v++;
}
}
}
System.out.println("Vowels:"+ v);
System.out.println("Consonants:" + (sentence.length -v));
One easy way would be to create 2 lists:
one contains vowels (a, e, i, o, u)
the other contains consonants
Then you iterate over each character in the Java string.
See a sample below:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Counter {
public static void main(String[] args) {
String test = "the fox is in the woods";
test = test.toLowerCase();
List<Character> vowels = new ArrayList<Character>();
vowels.addAll(Arrays.asList(new Character[]{'a', 'e', 'i', 'o', 'u'}));
List<Character> consonants = new ArrayList<Character>();
consonants.addAll(Arrays.asList(new Character[]{'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'}));
int vcount = 0;
int ccount = 0;
for (int i = 0; i < test.length(); i++){
Character letter = test.charAt(i);
if (vowels.contains(letter)){
vcount ++;
} else if (consonants.contains(letter)){
ccount++;
}
}
System.out.println(vcount);
System.out.println(ccount);
}
}
You can do a range check to make sure it is a letter, then check if it one of the vowels:
if( ( a >= 'a' && a<= 'z' ) || ( a >= 'A' && a <= 'Z' ) )
{
// is letter
switch( a )
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'U': case 'u':
++v;
break;
default: // don't list the rest of the characters since we did the check in the if statement above.
++c;
}
}
Oh, there's certainly a much more readable way to do it. Not sure if that meets the "better" definition.
As a start, I'd suggest that you encapsulate what you have into methods that you can write once and call anywhere:
package misc;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ParseUtils get counts of vowels and consonants in sentence
* #author Michael
* #link https://stackoverflow.com/questions/24048907/how-can-i-check-how-many-consonants-and-vowels-there-are-in-a-sentence-in-java
* #since 6/4/2014 6:57 PM
*/
public class ParseUtils {
private static final String VOWEL_PATTERN_STR = "(?i)[aeiou]";
private static final Pattern VOWEL_PATTERN = Pattern.compile(VOWEL_PATTERN_STR);
private static final String CONSONANT_PATTERN_STR = "(?i)[b-df-hj-np-tv-z]";
private static final Pattern CONSONANT_PATTERN = Pattern.compile(CONSONANT_PATTERN_STR);
private ParseUtils() {}
public static void main(String[] args) {
for (String arg : args) {
System.out.println(String.format("sentence: '%s' # letters: %d # vowels: %d # consonants %d", arg, arg.length(), getNumVowels(arg), getNumConsonants(arg)));
}
}
public static int getNumVowels(String sentence) {
return getMatchCount(sentence, VOWEL_PATTERN);
}
public static int getNumConsonants(String sentence) {
return getMatchCount(sentence, CONSONANT_PATTERN);
}
private static int getMatchCount(String s, Pattern p) {
int numMatches = 0;
if ((p != null) && (s != null) && (s.trim().length() > 0)) {
Matcher m = p.matcher(s);
while (m.find()) {
++numMatches;
}
}
return numMatches;
}
}
Split the String by whitespaces and and Calculate only the number of Vowels. Then Number of consonants = Length of Sentence - No. of Vowels.
Detailed Code:
System.out.println("Please enter the sentence to analyze: ");
int v = 0;
int c = 0;
String string = key.nextLine(); //the sentence the user inputs
String[] stringArray = string.split(" ");
for(int i=0;i<stringArray.length;i++)
{
for(int j= 0; j<string.length(); j++)
{
char a = string.charAt(j);
if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o'
|| a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y')
v = v + 1;
}
c= c+(stringArray.length)-v;
}
System.out.println("Vowels:"+v+" and Consonants:"+c);
One way to do it is to get rid of the non-letters, then vowels and consonants, and get the length of what is left:
public class CountChars {
public static final String CONSONANTS = "[BCDFGHJKLMNPQRSTVWXYZ]";
public static final String VOWELS = "[AEIOU]"; // considering Y a consonant here
public static final String NOT_LETTERS = "[\\W_0-9]";
public static void main(String[] args) {
String words = "How can I check how many consonants and vowels there are in a sentence in Java?";
String letters = words.toUpperCase().replaceAll(NOT_LETTERS, "");
System.out.println("Letters: " + letters.length());
String vowels = letters.replaceAll(CONSONANTS, "");
System.out.println("Vowels: " + vowels.length());
String consonants = letters.replaceAll(VOWELS, "");
System.out.println("Consonants: " + consonants.length());
}
}
Here is the best way of doing this:
public static void checkVowelsAndConsonants(String s){
System.out.println("Vowel Count: " + (s.length() - s.toLowerCase().replaceAll("a|e|i|o|u|", "").length()));
//Also eliminating spaces, if any for the consonant count
System.out.println("Consonant Count: " + (s.toLowerCase().replaceAll("a|e|i|o| |u", "").length()));
}

Categories

Resources