在字符串中统计特定字符串的个数

来源:互联网 发布:java线程池的使用 编辑:程序博客网 时间:2024/05/16 08:10

      我不是大神,也不是天才,所以,很多东西都是靠自己的后天的努力才能学到。有时候挺羡慕那些学霸们的,或者说天才们的,他们平日里上课轻轻松松学习,回到寝室可以玩玩游戏,只需要复习点,看点书就可以写出代码出来了。所以,他们一直是同学或者小伙伴们崇拜的对象。不象我等,花了多少个日夜,熬了多少个晚上,就是为了debug一个程序,甚至都熬出病来了,熬得肾虚了。

       在孔乙己的眼中"茴香豆"的"茴"有四种写法,所以本菜鸟也来写一个在字符串中搜索子串的三种算法。本人是比较愚笨的,笨鸟就懂得先飞,才能与小伙伴一起到达光明的彼岸。爬到金字塔顶端有两种动物:一种是雄鹰,另一种是蜗牛。
                                                                                                                                                                    --2014.11.22
问题描述:

编写一个方法,输出一个字符串在另一个字符串中出现的次数,如:在字符串"jajjjajaaajjllljlljljljja"中,"ja"子串出现的数次是:4次

方法一:

利用标记i符号,记录源字符串的位置,如果子串的首字母存在则比较,k才是实事移动的元素的下标。这考验着一个coder的算法和码代码水平,jdk已经提供相应的api,硬编码在学习基础编程中有利于自己的提高。

public class Test3 {public static void main(String[] args) {String str = "thisthisisthejavaprogrammer,andnicetousethisproram,isis";        String str4Find = "this";        int count = 0;        for(int i = 0; i < str.length(); i++) {        char des = str4Find.charAt(0); //取出目的字符串的第一个字符,若在str存在,则继续比较,否则忽略            if(str.charAt(i) == des) {            boolean flag = true;                for(int j = 0; j < str4Find.length(); j++,i++) {                if(str.charAt(i) != str4Find.charAt(j)) {                flag = false;                break;                }                }                if(flag) {                count++;                    i--;                }            }         }         System.out.println(str);         System.out.println("包含字符串:" + str4Find + "个数:" + count);} }

还是方法一:

class Method1 {public static void main(String[] args) {String str = "javahahajavajavahehejavjavailovejava";String str4Find = "java"; int count = 0;for(int i = 0; i < str.length(); i++) {int j = 0;int k = i;while(j < str4Find.length() && str.charAt(k) == str4Find.charAt(j)) {k++;j++;}if(j == str4Find.length()) {count++;}}System.out.println("在字符串中,包含子串" + str4Find + "的个数:" + count);} }
    while循环一定要要把数组越界的判断放在前面,然后来判断两个字符是否匹配,否则将会出现
数组越界的错误。还有就是注意while循环的两个终止条件。
 
方法二:调用String类的方法indexOf()返回子串所在的索引

public class Method2 {public static void main(String[] args) {String str = "jajjjajaaajjllljlljljljja";String str4Find = "ja";int count = 0;int index = str.indexOf(str);while(index != -1) {count++;index = str.indexOf(str4Find, index+str4Find.length());}System.out.println("在字符串中包含子串" + str4Find + "的个数:" + count);} }

方法三:用String类中的substring,当str开头的第一个字符不是str4Find的首字符的时候,就将str的第一个字符去掉,如果str的长度小str4Find的长度的时候,就没有必要找下去了。

public class Method3 {public static void main(String[] args) {String str ="nihaookhuozhebuok?ok!";String str4Find = "ok"; int count = 0;int index = str.indexOf(str4Find);while(index != -1) {if(str.indexOf(str4Find) == 0) {count++;str = str.substring(str4Find.length());} else {str = str.substring(1);}if(str.length() < str4Find.length()) {break;}}System.out.println("在字符串中,子串" + str4Find + "出现次数:" + count);} }

1 0