0

I want to find vowels positions in the string. How can I make shorter this code?

I tried contains and indexOf method but couldn't do it.

        String inputStr = "Merhaba";

        ArrayList<Character> vowelsBin = new ArrayList<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
        ArrayList<Integer> vowelsPos = new ArrayList<Integer>();

        for (int inputPos = 0; inputPos < inputStr.length(); inputPos = inputPos + 1)
        for (int vowelPos = 0; vowelPos < vowelsBin.size(); vowelPos = vowelPos + 1)
        if (inputStr.charAt(inputPos) == vowelsBin.get(vowelPos)) vowelsPos.add(inputPos);

        return vowelsPos;
Mestedepsu
  • 35
  • 4
  • 2
    You can use a regex to get all indexes. Try the accepted answer here:[SO: Find all indexes using regex](https://stackoverflow.com/questions/8938498/get-the-index-of-a-pattern-in-a-string-using-regex). – Alias Cartellano Oct 18 '21 at 18:39

1 Answers1

1

I assume you want to get m2rh5b7 from your input string Merhaba based on your code, then the below works fine,

        String input = "Merhaba";
        StringBuilder output = new StringBuilder();
        for(int i = 0; i < input.length(); i++){
           char c = input.toLowerCase().charAt(i);
           if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
               output.append(i+1);
           } else {
               output.append(c);
           }
        }
        System.out.println(output);  // prints --> m2rh5b7

Or if you want just position of the vowels position only, the below is fine,


        String input = "Merhaba";
        for(int i = 0; i < input.length(); i++){
           char c = input.toLowerCase().charAt(i);
           if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
               System.out.println(i);
           }
        }

you can use regex also, please refer the above from Alias.

prostý člověk
  • 909
  • 11
  • 29