0

我想在字符串中找到元音位置。我怎样才能缩短这段代码?

我尝试了 contains 和 indexOf 方法,但做不到。

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

1 回答 1

1

我假设你想根据你的代码m2rh5b7从你的输入字符串中获取Merhaba,那么下面的工作正常,

        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

或者如果你只想要元音位置的位置,下面就可以了,


        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);
           }
        }

您也可以使用正则表达式,请参考 Alias 的上述内容。

于 2021-10-18T20:12:53.167 回答