I have to remove all vowels from a string using a for loop.
I have this declaration so I can just call VOWELS.
public static final String VOWELS = "aeiouAEIOU";
I'm just not sure how to return the string with no vowels in it but keep the vowel if starts the word.
This is what I have so far:
public static String stringCompress(String msg){
String rtn = "";
for(int i = 1; i < msg.length(); i ){
if(Character.isWhitespace(i)){
rtn = (char)(msg.charAt(i - 1);
}
else if(VOWELS.contains(msg.valueOf(i))){
rtn = msg.charAt(i);
}
}
return rtn;
}
but it's not returning what I need it to. its returning [be a r, if]
I am just really confused. Any suggestions would help.
CodePudding user response:
Removing vowels from a string unless the vowel starts the word using a for loop
You are making several mistakes.
- you don't want to use
valueOf
. UsecharAt()
- As easy way to determine start of word is to save the previous character for testing as a space. So initialize it to a space.
- then if the previous char was not a space (i.e. not start of word) and the current character is a vowel, ignore it.
- otherwise append it to the return string.
- continue until the loop is done (which should start at 0 and not 1).
String test = "Animal Horse Elephant Dog cat ";
System.out.println(stringCompress(test));
prints
Anml Hrs Elphnt Dg ct
- Use a
StringBuilder
to house the result lastChar
is used to determine if it was preceded by a white space.
public static String stringCompress(String msg) {
StringBuilder sb = new StringBuilder();
char lastChar = ' ';
for (int i = 0; i < msg.length(); i ) {
char c = msg.charAt(i);
if (!VOWELS.contains(c "")
|| Character.isWhitespace(lastChar)) {
sb.append(c);
}
lastChar = c;
}
return sb.toString();
}
CodePudding user response:
You can try using StringBuilder :
public static String stringCompress(String msg) {
StringBuilder rtn = new StringBuilder("");
for (int i = 0; i < msg.length(); i ) {
if (Character.isWhitespace(i) || !VOWELS.contains(msg.charAt(i) "")) {
rtn.append(msg.charAt(i));
}
}
return rtn.toString();
}
CodePudding user response:
Try this, look at the isWhitespace
line, maybe that is your problem:
public static String stringCompress(String msg){
String rtn = "";
for(int i = 1; i < msg.length(); i ){
if(Character.isWhitespace(msg.valueOf(i))){
rtn = (char)(msg.charAt(i - 1);
}
else if(VOWELS.contains(msg.valueOf(i))){
rtn = msg.charAt(i);
}
}
return rtn;
}