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