1.手动实现
public class Test {
public static String my_toLowerCase(String str) {
String ret = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z') {
ch = (char) (ch + 32);
ret = ret + ch;
} else {
ret = ret + ch;
}
}
return ret;
}
public static void main(String[] args) {
String str = "hello 123 BAIXIAN";
String ret = my_toLowerCase(str);
System.out.println(ret);
}
}
此外,实际上在实现my_toLowerCase
过程中new了很多对象,这是效率非常低的,可以采用SringBuilderl类型,这样本身去调用append方法就效率高一些
public class Test {
public static String my_toLowerCase(String str) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z') {
ch = (char) (ch + 32);
stringBuilder.append(ch);
} else {
stringBuilder.append(ch);
}
}
return stringBuilder.toString();
}
public static void main(String[] args) {
String str = "hello 123 BAIXIAN";
String ret = my_toLowerCase(str);
System.out.println(ret);
}
}
2.利用Java中String的原生方法
public class Test {
public static void main(String[] args) {
String str1 = "HELLO,你好";
String str2 = "hello,你好";
String str3 = "HEllo";
System.out.println(str2.toLowerCase());//转换成小写
System.out.println(str2.toUpperCase());//转换成大写
System.out.println(str3.toLowerCase());
}
}