下面的代码是将大写字母转换为小写字母,反之亦然?
if(s1.charAt(i)>=97 && s1.charAt(i)<=122){
s1.charAt(i)=s1.charAt(i)-32;
}
else if(s1.charAt(i)>=65 && s1.charAt(i)<=90){
s1.charAt(i)=s1.charAt(i)+32;
}
请引用上面的内容并帮忙看看这个程序有什么问题?
最佳答案
您遇到了问题:
s1.charAt(i) = s1.charAt(i) - 32;
------------ -----------------
1 2
这里有两个问题:
- 首先,第二部分返回一个 int,然后尝试将其分配给一个 char
- 其次,你不能进行这样的分配
相反,我会使用:
String s1 = "AbCd";
//create a char array
char[] array = s1.toCharArray();
//loop over this array, and work just with it
for (int i = 0; i < array.length; i++) {
if (array[i] >= 'a' && array[i] <= 'z') {
array[i] = (char) (s1.charAt(i) - 32);//<--------------------------note this
} else if (s1.charAt(i) >= 'A' && s1.charAt(i) <= 'Z') {
array[i] = (char) (s1.charAt(i) + 32);
}
}
//when you end, convert that array to the String
s1 = String.valueOf(array);//output of AbCd is aBcD
<小时/>
此外我想使用:
String result = "";
for (int i = 0; i < array.length; i++) {
if (Character.isLowerCase(array[i])) {
result += Character.toUpperCase(s1.charAt(i));
} else {
result += Character.toLowerCase(s1.charAt(i));
}
}
关于java - 大小写转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51099237/