Find the number of identical characters in a string

Use substring to intercept strings and use indexof to find characters

String str;

str=str.substring(int beginIndex); Intercept the string whose length is beginIndex from the first letter of str, and assign the remaining string to str;

str=str.substring(int beginIndex, int endIndex); Intercept the string from beginIndex to endIndex in str, and assign it to str;

The indexOf method gets the position where the specified character appears for the first time in the string, and returns -1 if the entire string is not found

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325479705&siteId=291194637