`

【练习】判断一个字符串中某些字段出现的次数

 
阅读更多
package com.heima.test;

import java.io.*;

public class wordtext {
	public static void main(String[] args) {
		String s = " ";
		String w = " ";
		System.out.print("input:\n");
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					System.in));
			s = in.readLine();
			System.out.println(s);
		} catch (IOException e) {
		}
		System.out.print("input text word!");
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					System.in));
			w = in.readLine();
			System.out.println(w);
		} catch (IOException e) {
		}
		

		int wLen = w.length();
		int sLen = s.length();	
		int beginIndex = 0;
		int endIndex = wLen;
		int count = 0;
		//sLen - wLen就是走过的距离
		for(int i = 0; i < sLen - wLen; i++){
			String word = s.substring(beginIndex, endIndex);
			if(word.equalsIgnoreCase(w)){
				count++;
			}
			beginIndex++;
			endIndex++;
		}	
		if (count == 0)
			System.out.println("there no " + w);
		else
			System.out.println("there" + count + w);
		
		
//		int first = 0, second = 0, end = 0;
//		for (int i = 1; i <= s.length(); i += second + 1) {
//			second = s.indexOf(" ");
//			String t = s.substring(first, second);
//			s = s.substring(second + 1);
//			if (w.equalsIgnoreCase(t))
//				end++;
//		}
//		if (end == 0)
//			System.out.println("there no " + w);
//		else
//			System.out.println("there" + end + w);
	}
}


是别人提出问题代码后,我修改后得出的,有不足,不是自己的就没去改了
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics