Remove all vowels in a string with Java

久未见 提交于 2019-12-01 22:24:10
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:

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 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

  • Iterate over the character array of your String
  • If you hit a vowel skip the index and copy over the next non vowel character to the vowel position.
  • You will need two counters, one which iterates over the full string, the other which keeps track of the last vowel position.
  • After you reach the end of the array, look at the vowel tracker counter - is it sitting on a vowel, if not then the new String can be build from index 0 to 'vowelCounter-1'.

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 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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!