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

本文介绍了一个Java程序,该程序能够从键盘输入接收字符串,实现大小写字母的转换,非字母字符替换为星号,并统计字母数量。示例展示了如何使用Scanner类读取用户输入,遍历字符串字符进行条件判断和转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值