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;
	}
}

你可能感兴趣的:(java)