* 1.有且仅有一个"@qq.com"作为结尾,忽略大小写
* 2.QQ号不能以0开头,范围在6位到10位之间
* 例如:123456@QQ.com
public void test1(){
//待验证的邮箱
String email ="1234456@QQ.com";
//先同一字符为全小写
String lowerEmail =email.toLowerCase();
//只出现一次,使用indexOf和lastIndexOf判断是否为同一位置
//以xxx结尾,使用endsWith
if(lowerEmail.indexOf("@qq.com")==lowerEmail.lastIndexOf("@qq.com")&&lowerEmail.endsWith("@qq.com")){
//截取QQ号,使用split根据@qq,com切分的第一段字符串
String qq=lowerEmail.split("@qq.com")[0];
//6至10位且0不能开头
if(qq.length()>=6&&qq.length()<=10&&qq.charAt(0)!='0') {
System.out.println("格式正确!");
}else {
System.out.println("格式有误!");
}
}else {
System.out.println("请以@qq.com结尾,接只能出现一次");
}
}
第二题:
* 输入一段英文,将每个单词的首字母大写,并重新输出
public void test7(){
System.out.println("请输入一段英文短语");
Scanner sc = new Scanner(System.in);
//使用sc.nextLine()才能接收包含空格的字符串
String inp = sc.nextLine();
//拆分短语中的单词
String[] wordList = inp.split(" ");
String res = "";
//遍历每个单词
for (String word : wordList) {
//获取每个单词的首字母后转换为大写
char c = word.charAt(0);
//String.valueOf(参数)表示将一个参数转换为字符串
String firstLetter = String.valueOf(c).toUpperCase();
//从第二个字母开始截取至末尾
String lastLetter = word.substring(1);
res += firstLetter + lastLetter + " ";
}
System.out.println(res.trim());
}
第三题:
其他字符串的一些用法
public void test6(){
String str = " Hello World 你";
//获取字符串的长度,实际就是字符串中字符的数量,空格也算
System.out.println(str.length());
//去除字符串首尾所有空格
System.out.println(str.trim());
//将字符转换为大写
System.out.println(str.toUpperCase());
//将字符串转换为小写
System.out.println(str.toLowerCase());
//判断一个字符串是否为空字符串,实际就是判断字符数量是否为0
System.out.println(str.isEmpty());
//""就是一个空字符串
System.out.println("".isEmpty());
//按默认编码格式将字符串转换为字节数组,英文字母转换按ascii码表转换
//中文一个汉字用3个byte数表示(utf-8)
for (byte aByte : str.getBytes()) {
System.out.print(aByte + ",");
}
System.out.println();
//将字符串转换为char数组
for (char c : str.toCharArray()) {
System.out.print(c + ",");
}
System.out.println();
//获取某个索引对应的字符
System.out.println(str.charAt(1));
//获取某个字符第一次出现的索引
System.out.println(str.indexOf("l"));
//获取某个字符最后一次出现的索引
System.out.println(str.lastIndexOf("l"));
//可以获取子串的索引,子串是一个整体
System.out.println(str.lastIndexOf("He"));
//获取某个不存在的字符的索引时,返回-1
System.out.println(str.indexOf("t"));
//验证是否存在指定字符序列(字符串)
System.out.println(str.contains("lol"));
//将指定字符串拼接到原字符串末尾
System.out.println(str.concat("xxx"));
//验证是否以指定字符串开头
System.out.println(str.startsWith(" He"));
//验证是否以指定字符串结尾
System.out.println(str.endsWith("你"));
//将原字符串从指定位置开始截取子串至末尾[index,length)
System.out.println(str.substring(7));
//将原字符串从指定位置开始截取子串到另一个位置[begin,end)
System.out.println(str.substring(3,6));
//如果指定字符串不在末尾,n个字符串,能得到n+1个子串
//如果指定字符串在末尾,n个字符串,能得到n个子串,不算最后的无效字符
String[] list = str.split(" ");
System.out.println(list.length);
for (String s : list) {
System.out.print(s+",");
}
System.out.println("n------------");
System.out.println(str);
//如果要使用.作为分割的标识,需要使用转义字符\.
System.out.println("a.b.c".split("\.").length);
}
结果:



