关于String类的大小写转换问题

imkevin2011 2017-08-28 12:56:52
import java.util.Scanner;

public class pra4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入字符串:");
String sc1 = sc.next();
System.out.println(chan(sc1));
}
//遍历字符串赋值给char c,
public static String chan(String sc2){
for(int i = 0; i < sc2.length(); i++){
char c = sc2.charAt(i);
String str = sc2.substring(i,i+1);
if(c >= 65 && c <= 90){
str.toLowerCase();
}else if(c >= 97 && c <= 122){
str.toUpperCase();
}else{
str = "*";
}
}
return sc2;
}
}

需求是这样的:用户输入字符串,大写转换为小写,小写转换为大写,其余字符转换成*.
我试了好多方法啊,一开始是转char c无效,然后又怀疑自己asacii码记错,最后用了substring这个方法,让他去调用大小写转换方法,结果都无效,是哪里出了问题呢?
...全文
300 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Freefish1994 2017-08-28
  • 打赏
  • 举报
回复
写了一个你可以参考一下 还有就是楼主应该使用nextLine()来接收字符串 因为如果输入的是“abc F123”这种中间有空格的,next()方法会直接把空格之后的字符串过滤掉,显示得就不完整了

public class Test {
	
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("输入字符串:");
		String source = scanner.nextLine();
		System.out.println(transform(source));
		scanner.close();
	}

	private static String transform(String source) {
		char[] temp = source.toCharArray();
		for (int i = 0; i < temp.length; i++) {
			if (temp[i] <= 122 && temp[i] >= 97)
				temp[i] = Character.toUpperCase(temp[i]);
			else if (temp[i] <= 90 && temp[i] >= 65)
				temp[i] = Character.toLowerCase(temp[i]);
			else
				temp[i] = '*';
		}
		return new String(temp);
	}
	
}
黑夜点点白 2017-08-28
  • 打赏
  • 举报
回复
鱿鱼ing 2017-08-28
  • 打赏
  • 举报
回复
不要直接返回sc2 在chan方法里 new StringBuffer(); 没转换一个char 就 sb.append 一下 最后返回 sb.toString

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧