01
/**
02
*"In the entirehttp://zzdxjyzd.com world there's nobody like me.
03
*Since the beginning of time, there has never been another person like me.
04
*Nobody has my smile.
05
*Nobody has my eyes, my nose, my hair, my hands, or my voice."
06
* 要求:用户输入一个单词,求出在这段话中出现的次数?
07
08
* 我的思路:
09
* 1.寻找一个字符串短语在一段字符串中出现几次,首先肯定是用str.indexOf("my",start)方法
10
* 2.indexOf方法的返回值是int,如果找不到就会返回-1
11
* 3.利用这一点,可以设定一个循环,并定义一个计数器,
12
* 让计算机从段落的起始,一直找到末尾,如果找到一个就计数器+1,直到indexof返回结果为-1时,
13
* 停止循环.
14
* 4.注意:每一次开始找的位置,是不确定的.每一次的新位置,都是上一次找到"短语的位置"+"短语的长度"
15
*/
16
public class IndexDemo {
17
18
public static void main(String[] args) {
19
Scanner scan = new Scanner(System.in);
20
String str = "In the entire world there's nobody like me. "
21
+ "\nSince the beginning of time, "
22
+ "there has never been another person like me."
23
+ "\nNobody has my smile. \nNobody has my eyes, "
24
+ "my nose, my hair, my hands, or my voice.";
25
int count = 0;
26
System.out.println("请输入需要查找的单词:");
27
String key = scan.next();
28
count = serachWord(str,key);
29
System.out.println("短语my在段落中出现"+count+"次");
30
}
31
32
33
/**
34
* 查找某个单词在段落中出现次数的方法
35
* @param str
36
* @return
37
*/
38
/**
39
* @param str
40
* @param key
41
* @return
42
*/
43
public static int serachWord(String str,String key) {
44
//记录查找次数
45
int count = 0;
46
//记录每次查找的下标位置,初始化
47
int index = 0;
48
//定义循环,如果index的位置不是-1,就一值查找
49
while((index = str.indexOf(key,index))!=-1){
50
51
//每循环一次就要明确下一次查找的位置
52
index = index+key.length();
53
//每查找一次计数器自增
54
count ++;
55
}
56
return count;
57
}
58
}