Java statistics The number of occurrences of a substring in a specified string

Source: Internet
Author: User
Tags first string

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.