Files
javaSE-0113/day08/src/com/inmind/string01/Test06.java

43 lines
1.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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