Today, we used several methods in the string class to share the code.
Title Requirement: Count the number of occurrences of a substring in a specified string (prompting the Java string to appear 6 times)
1 Public classsearchsamestring {2 3 Public Static voidMain (string[] args) {4 //define two strings5String shortstr = "java";6String longstr = "Javasdfjavawerjavavsswetjavadfgdfgjavadfgdfbtujava";7 //calling the Searchcount method8 intCount =Searchcount (Shortstr, longstr);9 //number of occurrences of the output stringTenSystem.out.println ("The number of Java occurrences is:" +count); One A } - - //define the Searchcount method to return the number of occurrences of a string the Public Static intSearchcount (String shortstr, String longstr) { - //defines a count to hold the number of occurrences of a string - intCount = 0; - //invokes the indexof (String str) method of the string class, returning the index of the first occurrence of the same string + while(Longstr.indexof (SHORTSTR)! =-1) { - //if the same string is present, the number of times plus 1 +count++; A //Call the substring (int beginindex) method of the string class to get the first string after the same character appears atLongstr =longstr.substring (Longstr.indexof (SHORTSTR) -+shortstr.length ()); - - } - //number of returns - returncount; in } - to}
Java statistics The number of occurrences of a substring in a specified string