Programming

字母替換成下一個字母

字母替換成下一個字母

<解題>


public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();

        String string = "pineappleTREE"; //預期輸出pineaqpleUREE

        System.out.println(solution.replaceNextCharacter(string,3));

    }

}

class Solution {
    public String replaceNextCharacter(String string, Integer n) {
        if (string == null || string.length() == 0)
            return null;

        String result = "";
        int nonVowelCount = 0;  // 非母音字母數

        for (int i = 0; i < string.length(); i++) {
            char currentChar = string.charAt(i);
            if ("aeiouAEIOU".indexOf(currentChar) >= 0) {  // 使用indexOf判斷是否為母音
                int index = "aeiouAEIOU".indexOf(currentChar);
                result += currentChar;
            } else {
                nonVowelCount++;
                if (nonVowelCount % n == 0) {
                    if (currentChar >= 'a' && currentChar <= 'z') {
                        if (currentChar == 'z') {
                            result += 'a';
                        } else {
                            result += (char) (currentChar + 1);
                        }
                    } else if (currentChar >= 'A' && currentChar <= 'Z') {
                        if (currentChar == 'Z') {
                            result += 'A';
                        } else {
                            result += (char) (currentChar + 1);
                        }
                    } else {
                        result += currentChar;  //非字母
                    }
                } else {
                    result += currentChar;
                }
            }
        }
        return result;
    }
}