The instructions >>
Implement the method named removeVowels
which processes the array of strings named words
by printing each string from words
with only non-vowels on its own line.
For example, if words contains:
{"every", "nearing", "checking", "food", "stand", "value"}
The method should output:
vry
nrng
chckng
fd
stnd
vl
So far, I have:
public class U6_L3_Activity_Two {
public static void removeVowels(String[] hit_str) {
char vowels = {
'a',
'e',
'i',
'o',
'u',
'A',
'E',
'I',
'O',
'U'
};
for (int i = 0; i < hit_str.length; i ) {
if (find(vowels.begin(), vowels.end(),
hit_str[i]) != vowels.end()) {
hit_str = hit_str.replace(i, 1, "");
i -= 1;
}
}
return hit_str;
}
}
Runner:
import java.util.Scanner;
public class runner_U6_L3_Activity_Two
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter array length:");
int len = scan.nextInt();
scan.nextLine();
String[] wordList = new String[len];
System.out.println("Enter values:");
for(int i = 0; i < len; i )
{
wordList[i] = scan.nextLine();
}
U6_L3_Activity_Two.removeVowels(wordList);
}
}
The error message i'm getting says:
U6_L3_Activity_Two.java:3: error: illegal initializer for char
char vowels = {
^
I've tried a bunch of different ways to make a list of vowels but none of them seem to work.
CodePudding user response:
Try replacing vowels with this built-in method:
String[] hit_str = { "every", "nearing", "checking", "food", "stand", "value" };
for (String str : hit_str) {
System.out.println(str.replaceAll("[AaEeIiOoUu]", ""));
}
Here, the for
loop iterates over your input string/s and uses Regex
to check if char(s) is/are found from the provided Regex
. [AaEeIiOoUu]
tries to match all chars of Regex
individually in the string chars. Using Regex
is better than declaring a char[]
as it improves code readability and saves us from writing complex logics.
CodePudding user response:
There're many way to do this. I reccomen to split 2 tasks: remove vowels and print the results.
In case you are able to modife the original array, you can avoid creation of the new one.
public static String[] removeVowels(String[] words) {
String[] res = new String[words.length];
for (int i = 0; i < words.length; i ) {
String word = words[i];
StringBuilder buf = new StringBuilder(word.length());
for (int j = 0; j < word.length(); j ) {
char ch = word.charAt(j);
char lowerCase = Character.toLowerCase(ch);
if (lowerCase != 'a' && lowerCase != 'e'
&& lowerCase != 'i' && lowerCase != 'o'
&& lowerCase != 'u')
buf.append(ch);
}
res[i] = buf.toString();
}
return res;
}