day08-常用类_String的练习1

This commit is contained in:
2026-01-20 15:28:30 +08:00
parent 8316fbd2f2
commit 33aca26c55
2 changed files with 76 additions and 0 deletions

View File

@@ -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;//返回查找到的次数
}
}