统计子串数量
需求:
1.统计“abc”在字符串“abcdabcfgh”中出现的次数
2.借助于 int indexOf ( String str, int fromIndex )
代码实现:
public class Ex1 {
public static void main(String[] args) {
// 定义字符串
String s = "abcdabcfgh";
// 定义计数器
int count = 0;
// 定义索引值
int fromIndex = 0;
// 循环
while ((fromIndex = s.indexOf("abc", fromIndex)) != -1) {
// 计数器+1
count++;
fromIndex++;
}
// 输出结果
System.out.println("出现的次数"+count);
}
}
统计字符出现次数
需求:
1.遍历获取字符串中的每一个字符"abc001DEF"
2.统计该字符串中大写字母字符、小写字母字符,数字字符出现的次数(不考虑其他字符)
代码实现:
public class Ex2 {
public static void main(String[] args) {
// 定义字符串
String s = "abc001DEF";
// 定义计数器
int countUpper = 0;
int countLower = 0;
int countDigital = 0;
// 遍历字符串
for (int i = 0; i < s.length(); i++) {
// 取出来每个字符
char c = s.charAt(i);
// 做判断
if (c >= 'a' && c <= 'z') {
countLower++;
} else if (c >= 'A' && c <= 'Z') {
countUpper++;
}else{
countDigital++;
}
// 相应计数器+1
}
// 循环结束
// 输出结果
System.out.println("小写:"+countLower);
System.out.println("大写:"+countUpper);
System.out.println("数字:"+countDigital);
}
}