AsiaInfo technology pen questions, Asiainfo pen questions
I don't know if this question is an original question of AsiaInfo technology. It seems that Microsoft's written examination also has this question on the Internet. The original question was solved in C language. Considering java proficiency, I had java to write the algorithm for this question.
Topic Description: compile an algorithm to determine the number of times a string appears in another string. For example, the string "this" is in the string "this is my first program, this ..." Does not use library functions (methods ).
Solution: Write a static method, first retrieve the first letter of the string to be searched, and then get it to search for it. When a letter appears in the string that matches the first letter to be searched, we will mark it and then compare it with the remaining characters. The four characters are consistent, and the counter variable count is auto-incrementing.
public class FindStr { public static void main(String[] args) { String strToFind = "this"; String str = "this,this thi s my first program, this is my java..."; System.out.println(countAppea(strToFind, str)); } public static int countAppea(String str2Find, String str) { int count = 0; for(int i = 0; i < str.length(); i++) { char c = str.charAt(i); boolean flag = false; if(str2Find.charAt(0) == c) { flag = true; int index = i; for(int j = 0; j < str2Find.length(); j++, index++) { if(str2Find.charAt(j) != str.charAt(index)) { flag = false; break; } } if(flag) { count ++; } } } return count; }}
Running result:
3
Because there are four this in my string, one of which is accident-separated. So there are three this!