查询字符/字符串出现次数

  • Post author:
  • Post category:其他


//查找每个字符在字符串中出现的次数
    @org.testng.annotations.Test
    public void test24() {
        String str = "abcabcdefgABCD";
        lettercount3(str);

    }

    public static void lettercount3(String s) {

        System.out.println(s);
        List<String> list = Arrays.asList(s.split(""));
        Map map = new TreeMap();
        for (String str : list) {
            map.put(str, Collections.frequency(list, str));
        }
        System.out.println(map);

    }


    //查找A字符串在B字符串中出现的次数

//写法1
    @org.testng.annotations.Test
    public void test25() {

        int abc = get("abc", "abcdefabckkke;l,,,;l[p0ol;k,ml;klok/.,;kpokmmlok.abcjjjehfabc");
        System.out.println(abc);

    }

    public int get2(String a, String b) {
        int num = 0;
        while (b.contains(a)) {
            b = b.substring(b.indexOf(a) + a.length());
            System.out.println(b);
            num++;
        }
        return num;

    }


//效率更高的写法2
    @org.testng.annotations.Test
    public void test26() {
        int abc = get("abc", "abcdefabckkke;l,,,;l[p0ol;k,ml;klok/.,;kpokmmlok.abcjjjehfabc");
        System.out.println(abc);

    }

    public int get(String a, String b) {
        int count = 0;
        char[] aa = a.toCharArray();
        char[] bb = b.toCharArray();
        if (aa.length > bb.length) return 0;
        for (int i = 0; i < bb.length; i++) {
            int sign = i;
            boolean success = true;
            for (int j = 0; j < aa.length; j++) {
                if (sign >= bb.length) {
                    success = false;
                    break;
                }
                if (aa[j] == bb[sign]) {
                    sign++;
                } else {
                    success = false;
                    break;
                }

            }
        if (success) count++;
    }
        return count;
}

what are you doing?



版权声明:本文为m0_67480772原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。