Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
Example 1:
Input: “Hello” Output: “hello”
Example 2:
Input: “here” Output: “here”
Example 3:
Input: “LOVELY” Output: “lovely”
题意:把大写转换成小写,如果是小写,则保持小写。 方法:
涉及到的问题:
class Solution {
public String toLowerCase(String str) {
StringBuilder sb = new StringBuilder();
for(int i=0;i<str.length();i++){
char tmp = str.charAt(i);
if(tmp>=65 && tmp<=90)
tmp+=32;
sb.append(tmp);
}
return String.valueOf(sb);
}
}注意stringBuild转string要用String.valueOf(sb),或者使用sb.toString()

上面这算法内存开销比较大,看看评论区解答。
String本身就是字符数组,数组的最大优点就是适合查改,因此将String转为数组操作会更快更好。
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);
}解释: