查找字符串中相同字符的個數


利用substring對字符串進行截取,利用indexof查找字符

String str;

str=str.substring(int beginIndex);截取掉str從首字母起長度為beginIndex的字符串,將剩余字符串賦值給str;

str=str.substring(int beginIndex,int endIndex);截取str中從beginIndex開始至endIndex結束時的字符串,並將其賦值給str;

indexOf方法獲取到指定的字符在字符串中第一次出現的位置,如果搜完整個字符串都沒有則返回-1

public class A1 {
	public static void main(String args[]){
		String str = "awdcsapplemifrhnapplefsfjiaapplercr";
		String s="apple";
		int count=0;
		int index=str.indexOf(s);		
		if (str.indexOf(s)!=-1) {
			count++;
		}
		int leng=index+s.length();
		str=str.substring(leng);
		while (str.indexOf(s)!=-1) {
			index=str.indexOf(s);
			leng=index+s.length();
			str=str.substring(leng);
			count++;
		}
		System.out.println(count);
		
		
	}
}

 3


免責聲明!

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



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