Lowercase to Uppercase II

题目:

Implement an upper method to convert all characters in a string to uppercase.

You should ignore the characters not in alphabet.

分析:

惊闻java中的String和JS一样是immutable的,不能使用下标设置其中的某个char,如果想通过下标修改,需要使用string builder,如解法2中的例子。

除此之外,发现java有很多不错的method,例如Character.toUpperCase(); Character.isLowerCase()之类的。

String builder的具体内容在这里:https://www.zhihu.com/question/20101840

解法1:

public class Solution {
    /**
     * @param str a string
     * @return a string
     */
    public char upper(char character) {
        if (character < 97 || character > 122) {
            return character;
        }
        character -= 32;
        return character;
    } 

    public String lowercaseToUppercase2(String str) {
        // Write your code here
        String res = "";
        for (int i = 0; i < str.length(); i++) {
            char temp = str.charAt(i);
            temp = upper(temp);
            res += temp;
        }
        return res;
    }
}

解法2:

public class Solution {
    /**
     * @param str a string
     * @return a string
     */
    public String lowercaseToUppercase2(String str) {
        // Write your code here
        StringBuilder sb = new StringBuilder(str);
        for (int index = 0; index < sb.length(); index++) {
            char c = sb.charAt(index);
            if (Character.isLowerCase(c)) {
                sb.setCharAt(index, Character.toUpperCase(c));
            }
        }
        return sb.toString();
    }
}

results matching ""

    No results matching ""