java_字符串中子字符串出現的次數


分別在控制台輸入字符串和子字符串,並計算字符串中子字符串出現的次數。


  

/**
 * 
 */
package 作業0919;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringCount {

	public static void main(String[] args) {
		System.out.println("請輸入要計算的父串和子串:");
		Scanner scanner = new Scanner(System.in);
		String father = scanner.next();
		String son = scanner.next();
		int count = 0;
		// 方法一:

		while (son.length() <= father.length()) {
			if (father.indexOf(son) != -1) {
				father = father.substring(father.indexOf(son) + son.length(), father.length());
				count++;
			} else {
				break;
			}

		}
		System.out.println("方法一中:子串在父串中出現了" + count + "次");

		// 方法二:
		extracted(father, son, count);

		// 方法三:
		count = extracted1(father, son, count);
	}

	private static void extracted(String father, String son, int count) {
		// 方法一:
		int fromIndex = father.indexOf(son);

		while (fromIndex < father.length()) {

			if (father.indexOf(son, fromIndex) != -1) {
				count++;
				fromIndex = father.indexOf(son, fromIndex) + son.length();
			} else {
				break;
			}
		}
		System.out.println("方法二中:子串在父串中出現了" + count + "次");
	}

	private static int extracted1(String father, String son, int count) {
		Pattern p = Pattern.compile(son, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(father);

		while (m.find()) {
			count++;
		}
		System.out.println("方法三中:子串在父串中出現了" + count + "次");
		return count;
	}

}


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com