java查找字符串里與指定字符串相同的個數


public class EmployeeDemo {
	//方法一:
	public int search(String str,String strRes) {//查找字符串里與指定字符串相同的個數
		int n=0;//計數器
//		for(int i = 0;i<str.length();i++) {
//			
//		}
		while(str.indexOf(strRes)!=-1) {
			int i = str.indexOf(strRes);
			n++;
			str = str.substring(i+1);
		}
		return n;
	}
	//方法二:
	public int search2(String str,String strRes) {
		int n = 0;//計數器
		int index = 0;//指定字符的長度
		index = str.indexOf(strRes);
		while(index!=-1) {
			n++;
			index = str.indexOf(strRes,index+1); 
		}
		
		return n;
	}
	public static void main(String []args) {
		String arr = "朋友啊朋友,你現在怎么樣?";
		EmployeeDemo emp = new EmployeeDemo();
		System.out.println(emp.search(arr, "朋友"));
		System.out.println(emp.search2(arr, "朋友"));
	}
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM