Skip to content
Advertisement

How to get indexes of char in the string

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;

Advertisement

Answer

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.

Advertisement