键盘录入一个字符串要求长度为8不符合输出错误符合条件将字符串中所有大写字符替换成M
方式一:不使用正则
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//1.键盘录入一个字符串,包含大写字母
//2、输入字符串,替换所有的大写字母为“M”
Scanner sc = new Scanner(System.in);
System.out.print(“请输入字符串”);
String next = sc.next();
sc.close();
//2.定义新的字符串
String newStr = “”;
//3.遍历字符串
for (int i = 0; i < next.length(); i++) {
//4.获取每个字符
char charAt = next.charAt(i);
//5.判断当前字符是否为大写
//6.如果是大写字母,将大写M拼接到新的字符串中,如果是其他字符,直接拼接到新的字符串中
if(charAt>=‘A’ && charAt<=‘Z’){//大写字符
newStr+=‘M’;
}else{
newStr+=charAt;
}
}
//7.输出新的字符串
System.out.println(“next:”+next);
System.out.println(“newStr:”+newStr);
}
}
方式二:使用正则
import java.util.Scanner;
public class Test4 {
public static void main(String[] args) {
// 4、输入字符串,替换所有的大写字母为“M”
//1.键盘录入一个字符串,包含大写字母
Scanner sc = new Scanner(System.in);
System.out.print(“请输入字符串”);
String next = sc.next();//asfgQ4etAER
sc.close();
//2.使用正则
String regex = “[A-Z]”;
//3.调用字符串中替换的方法
String replaceAll = next.replaceAll(regex, “M”);
//4.输出新的字符串
System.out.println(“next:”+next);
System.out.println(“replaceAll:”+replaceAll);
}
}