LeetCode(String)709. To Lower Case

1.问题

Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.

Example 1:

Input: s = “Hello” Output: “hello”

Example 2:

Input: s = “here” Output: “here”

Example 3:

Input: s = “LOVELY” Output: “lovely”

Constraints:

1 <= s.length <= 100 s consists of printable ASCII characters.

2. 解题思路

方法1:

toLowerCase()直接将大写转换成小写

方法2:

1.把字符串转化为字符数组 2.判断字符是否为大写字母 3.把大写字母转化为小写字母 4.把字符数组转化为字符串并返回

3. 代码

代码1:

class Solution {
          
   
    public String toLowerCase(String s) {
          
   
        return s.toLowerCase();//toLowerCase()直接将大写转换成小写
        
    }
}

代码2:

class Solution {
          
   
    public String toLowerCase(String str) {
          
   
        char[] a = str.toCharArray(); // 把字符串转化为字符数组
        for (int i = 0; i < a.length; i++) {
          
   
            if (A <= a[i] && a[i] <= Z) {
          
    // 判断字符是否为大写字母
                a[i] = (char) (a[i] - A + a); // 把大写字母转化为小写字母
            }
        }
        return new String(a); // 把字符数组转化为字符串并返回
    }
}
解题思路相同
class Solution {
          
   
    public String toLowerCase(String str) {
          
   
        char[] chArray = str.toCharArray(); // 把字符串转化为字符数组
        for (int i = 0; i < chArray.length; i++) {
          
   
            if (chArray[i] >= A && chArray[i] <= Z) {
          
    // 判断字符是否为大写字母
                chArray[i] += 32; // 把大写字母转化为小写字母
            }
        }
        return String.valueOf(chArray); // 把字符数组转化为字符串并返回
    }
}
解释: 在ASCII编码中,大写字母的编码范围是65到90,小写字母的编码范围是97到122。因此,要把大写字母转化为小写字母,只需要将其对应的ASCII码值加上32即可。 在这个代码中,对于每一个大写字母,都执行了chArray[i] += 32的操作,即把该字符的ASCII码值加上32,从而把大写字母转化为小写字母。
经验分享 程序员 微信小程序 职场和发展