简体   繁体   中英

Using a for loop to remove vowels from a string

  1. Declare a string variable for the return value, and initialize it to "".
  2. Use a for loop to iterate over all the characters in the supplied string.
  3. Use a conditional or switch statement to check whether the character is a vowel.
  4. The vowels are 'a','e','i','o', and 'u', uppercase or lowercase.
  5. If it is a vowel, do nothing, otherwise add the character to the return string.
  6. After the loop has completed, return the string.

This is what I have so far, I'm new to this so any help would be appreciated.

public static String removeVowels(String input) {
    String s = "";
    int f = 0;


    for(int i = 0; i < input.length(); i++){

        if(c == 'a'|c == 'e'|c == 'i'|c == 'o'|c =='u' | c == 'A' | c == 'E' | c == 'I' | c == 'O' | c == 'U')
            f = 1;
        else{
            s = s + i;
            f = 0;
        }
    }
    return s;
}

With the for loop requirement:

private static String removeVowels(String s) {
    if (s == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    Set<Character> vowels = new HashSet<Character>();
    vowels.add('a');
    vowels.add('A');
    vowels.add('e');
    vowels.add('E');
    vowels.add('i');
    vowels.add('I');
    vowels.add('o');
    vowels.add('O');
    vowels.add('u');
    vowels.add('U');
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (!vowels.contains(c)) {
            sb.append(c);
        }
    }
    return sb.toString();
}

You could potentially pretty this up in a number of ways, but the above should work.

Without the for loop requirement:

public static String removeVowels(String input) {
    return input.replaceAll("[aAeEiIoOuU]","");
}
public class RemoveVowels { public static void main (String [] args) { String str = "Hello Good Morning"; String s1 = str.replaceAll("[AEIOUaeiou]" , ""); System.out.println(s1); } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM