The Java implementation counts the number of occurrences of a string in another string

Source: Internet
Author: User

This is often the subject of an interview, and it is not expected that regular expressions will be used. Fortunately this algorithm is still simple, but on the draft paper will inevitably appear to run the exception, well, the interviewer won, they are the real code of the wire out bar.

Here is the implementation code:

/** * Count the number of occurrences of a string in another string *  *  */public class Counthit {public static void main (string[] args) {string A = "123456a Bcde6ab "; String B = "6ABC"; System.out.println (New Counthit (). Hit (A, b)); /** *  * @param A * matched            long String * @param b *            matches short String * @return number of matches */public int hit (string A, string b) {if (a.le Ngth () < B.length ()) {return 0;} char[] a_t = A.tochararray (); char[] b_t = B.tochararray (); int count = 0, temp = 0, j = 0;for (int i = 0; i < a_t.length ; i++) {//Ensure that a continuous string B matches a segment in a if (a_t[i] = = B_t[j] && J < b_t.length) {temp++;j++;//This time the continuous string B matches a segment in a F (temp = = b_t.length) {count++;temp = 0;j = 0;}} As long as there is a character mismatch, the temp count is never else {temp = 0;j = 0;}} return count;}}

:)

The Java implementation counts the number of occurrences of a string in another 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.