day08-常用类-String-的获取方法_练习

This commit is contained in:
2026-05-16 14:20:50 +08:00
parent 7da8c2100f
commit b6bdce8620

View File

@@ -0,0 +1,36 @@
package com.inmind.string01;
import java.util.Scanner;
/*
字符串查找。
* 键盘录入一个大字符串,再录入一个小字符串。
* 统计小字符串在大字符串中出现的次数。
*/
public class Test05 {
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();
//调用统计次数的方法
int count = getCount(str, subStr);
System.out.println("出现的次数是:" + count);
}
//定义一个方法统计短字符串出现的次数(java123java java)
public static int getCount(String str, String subStr){
int count = 0;//统计次数
//循环查找indexOf, 如果返回-1则说明没有找到结束循环
//public int indexOf (String str)
int index = 0;//记录每次查找内容的索引便于下一次查找index+1
while ((index = str.indexOf(subStr, index)) != -1) {
count++;
index++;
}
return count;
}
}