AsiaInfo technology pen questions, Asiainfo pen questions

Source: Internet
Author: User

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!

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.