day08-常用类_String的练习1
This commit is contained in:
@@ -1,8 +1,50 @@
|
||||
package com.inmind.string01;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
/*
|
||||
键盘录入QQ号码,验证格式的正确性。
|
||||
* 必须是5—12位数字。
|
||||
* 0不能开头。
|
||||
*/
|
||||
public class Test05 {
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("请输入一个QQ号码:");
|
||||
String qq = sc.nextLine();
|
||||
//验证格式的正确性
|
||||
boolean result = checkQQ(qq);
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
/*
|
||||
* 必须是5—12位数字。
|
||||
* 0不能开头。
|
||||
*/
|
||||
public static boolean checkQQ(String qq) {
|
||||
//判断长度
|
||||
int length = qq.length();
|
||||
if (length < 5 || length > 12) {
|
||||
System.out.println("您输入的QQ号码,长度不符合");
|
||||
return false;
|
||||
}
|
||||
|
||||
//判断第一个字符是否为0
|
||||
if (qq.charAt(0) == '0') {
|
||||
System.out.println("您输入的QQ号码,首字符不能为0");
|
||||
return false;
|
||||
}
|
||||
|
||||
//判断QQ号码的每个字符都必须是‘0’~‘9’的字符
|
||||
for (int i = 0; i < qq.length(); i++) {
|
||||
char c = qq.charAt(i);//每个字符
|
||||
if (c < '0' || c > '9') {
|
||||
System.out.println("您输入的QQ号码,只能包含数字");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
//之前所有的条件都符合,那就是合格的QQ
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,42 @@
|
||||
package com.inmind.string01;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
/*
|
||||
字符串查找。
|
||||
* 键盘录入一个比较长的字符串,再录入一个子字符串。
|
||||
* 统计小字符串在大字符串中出现的次数。
|
||||
*/
|
||||
public class Test06 {
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("请输入第一个长字符串:");
|
||||
String str = sc.nextLine();
|
||||
System.out.println("请输入第二个短字符串:");
|
||||
String subStr = sc.nextLine();
|
||||
//查找subStr在str中出现的次数,indexOf()即可
|
||||
int count = getSubCount(str, subStr);
|
||||
System.out.println("子字符串出现的次数为:"+count);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param str 长字符串
|
||||
* @param subStr 子字符串
|
||||
* @return 出现的次数
|
||||
*/
|
||||
public static int getSubCount(String str, String subStr) {
|
||||
//定义一个变量记录出现的次数
|
||||
int count = 0;
|
||||
//记录每次查找到子内容的索引,便于下一次子内容的查找
|
||||
int index = 0;
|
||||
//不停地查找,直到找不到
|
||||
while ((index = str.indexOf(subStr,index)) != -1) {
|
||||
count++;//次数+1
|
||||
index++;
|
||||
}
|
||||
|
||||
return count;//返回查找到的次数
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user