I am doing a homework assignment for my Computer Science course. The task is to get a users input, remove all of the vowels, and then print the new statement.
I kno
I think you can iterate through the character check if that is vowel or not as below:
define a new string
for(each character in input string)
//("aeiou".indexOf(character) <0) id one way to check if character is consonant
if "aeiou" doesn't contain the character
append the character in the new string
If you want to do it in O(n) time
If you do this is in Java you will need extra space to build the new String etc. If you do it in C you can simply terminate the String with a null character and complete the program without any extra space.
I think what he might want is for you to read the string, create a new empty string (call it s
), loop over your input and add all the characters that are not vowels to s
(this requires an if
statement). Then, you would simply print the contents of s
.
Edit: You might want to consider using a StringBuilder for this because repetitive string concatenation can hinder performance, but the idea is the same. But to be honest, I doubt it would make a noticeable difference for this type of thing.
I don't think your instructor wanted you to call Character.isLetter('a')
because it's always true
.
The simplest way of building the result without regexp is using a StringBuilder
and a switch
statement, like this:
String s = "quick brown fox jumps over the lazy dog";
StringBuffer res = new StringBuffer();
for (char c : s.toCharArray()) {
switch(c) {
case 'a': // Fall through
case 'u': // Fall through
case 'o': // Fall through
case 'i': // Fall through
case 'e': break; // Do nothing
default: // Do something
}
}
s = res.toString();
System.out.println(s);
You can also replace this with an equivalent if
, like this:
if (c!='a' && c!='u' && c!='o' && c!='i' && c!='e') {
// Do something
}
Character.isLetter('a')
Character.isLetter(char) tells you if the value you give it is a letter, which isn't helpful in this case (you already know that "a" is a letter).
You probably want to use the equality operator, ==
, to see if your character is an "a", like:
char c = ...
if(c == 'a') {
...
} else if (c == 'e') {
...
}
You can get all of the characters in a String in multiple ways: