String练习题,字母转换大小写,字符替换

package cn.wang.day10; //import java.util.Arrays; import java.util.Scanner; /** * @author WangShiwu * *2.分析以下需求,并用代码实现: (1)从键盘循环录入录入一个字符串,输入"end"表示结束 *(2)将字符串中大写字母变成小写字母,小写字母变成大写字母,其它字符用"*"代替,并统计字母的个数 举例: *键盘录入:Hello12345World 输出结果:hELLO*****wORLD 总共10个字母 */ public class Demo02_HomeWork { public static void main(String[] args) {/*Scanner sc = new Scanner(System.in); System.out.println("请输入字符串,(end表示结束):"); String result = ""; while (true) { String str = sc.nextLine(); if(str.endsWith("end")) { result = str.substring(0, str.length() - 3); break; } } String num = ""; int count = 0; char[] ch = result.toCharArray(); for (int index = 0; index < ch.length; index++) { if (ch[index] >= 65 && ch[index] <=90) {//可以ch[index] >= 'A' && ch[index] <= 'Z' num = num + (ch[index] + "").toLowerCase(); count++; } else if (ch[index] >= 97 && ch[index] <= 122){//可以ch[index] >= 'A' && ch[index] <= 'z' num = num + (ch[index] + "").toUpperCase(); count++; } else { num = num + "*"; } } System.out.println("转换后的字符串为:" + num); System.out.println("总共" + count + "个字母"); sc.close(); *///法二 Scanner sc = new Scanner(System.in); System.out.println("请输入字符串,(end表示结束):"); while (true) { String str = sc.nextLine(); if ("end".equals(str)) { break; } int count = 0; char[] ch = str.toCharArray(); for (int index = 0; index < ch.length; index++) { if (ch[index] >= 'A' && ch[index] <= 'Z') { ch[index] += 32; count++; } else if (ch[index] >= 'a' && ch[index] <= 'z') { ch[index] -= 32; count++; } else { ch[index] = '*'; } } System.out.println("转换后的字符串为:" + new String(ch)); System.out.println("总共" + count + "个字母"); } sc.close(); } }

    推荐阅读