亚信科技笔试题

不清楚这道题是不是亚信科技的原创题目,貌似在网上看到微软的笔试也有这道题目。原题的是c语言解决的,考虑java熟练一些。自己就有java来写这道题的算法。
题目描写叙述:编写一个确定字符串在还有一个字符串中出现的次数的算法。

比如字符串“this”在字符串”this is my first program, this…”中出现了2次。不要使用库函数(方法)。
解题思路:写一个静态方法。先取出要查找的字符串的第一个字母,然后再拿到字符串中去搜寻,当字符串中出现字母与要查找的首字母吻合。我们就做标记。然后用剩余的字符逐步比較。四个字符都吻合,计数器变量count自增。

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;
    }
}

执行结果:
3
由于我的字符串里面有四个this,当中有一个事有益分开的。所以有三个this!

原文地址:https://www.cnblogs.com/mengfanrong/p/5132998.html