【问题标题】:How to get indexes of char in the string如何获取字符串中char的索引
【发布时间】:2021-12-05 18:41:27
【问题描述】:

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

我尝试了 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;

【问题讨论】:

标签: java indexing position contains


【解决方案1】:

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

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

你也可以使用正则表达式,请参考上面的别名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    相关资源
    最近更新 更多