zyjcxc
2016-04-28 00:20:25
java String.indexOf方法在一个字符串中查找另一个字符串的次数的简单应用
/** *"In the entire world there's nobody like me. *Since the beginning of time, there has never been another person like me. *Nobody has my smile. *Nobody has my eyes, my nose, my hair, my hands, or my voice." * 要求:用户输入一个单词,求出在这段话中出现的次数? * 我的思路: * 1.寻找一个字符串短语在一段字符串中出现几次,首先肯定是用str.indexOf("my",start)方法 * 2.indexOf方法的返回值是int,如果找不到就会返回-1 * 3.利用这一点,可以设定一个循环,并定义一个计数器, * 让计算机从段落的起始,一直找到末尾,如果找到一个就计数器+1,直到indexof返回结果为-1时, * 停止循环. * 4.注意:每一次开始找的位置,是不确定的.每一次的新位置,都是上一次找到"短语的位置"+"短语的长度" */ public class IndexDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String str = "In the entire world there's nobody like me. " + "\nSince the beginning of time, " + "there has never been another person like me." + "\nNobody has my smile. \nNobody has my eyes, " + "my nose, my hair, my hands, or my voice."; int count = 0; System.out.println("请输入需要查找的单词:"); String key = scan.next(); count = serachWord(str,key); System.out.println("短语my在段落中出现"+count+"次"); } /** * 查找某个单词在段落中出现次数的方法 * @param str * @return */ /** * @param str * @param key * @return */ public static int serachWord(String str,String key) { //记录查找次数 int count = 0; //记录每次查找的下标位置,初始化 int index = 0; //定义循环,如果index的位置不是-1,就一值查找 while((index = str.indexOf(key,index))!=-1){ //每循环一次就要明确下一次查找的位置 index = index+key.length(); //每查找一次计数器自增 count ++; } return count; } }
运行结果如下:
猜你喜欢
请下载代码后再发表评论



wangyaoM LV2
2021年6月2日
13232875251 LV14
2020年7月28日
new_docker LV15
2020年7月26日
zzyala LV6
2020年7月20日
逆袭 奋起 LV4
2020年7月12日
ls2008 LV15
2020年6月28日
小学生波波 LV19
2020年6月8日
zhangtian1997 LV10
2020年6月7日
加油干阳神 LV9
2020年5月2日
zfdfggg LV2
2020年4月26日