我有字符串

a.b.c.d

我想数一下'的出现次数。,最好是一句单句俏皮话。

(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。


当前回答

这个怎么样。它没有在底层使用regexp,因此应该比其他一些解决方案更快,并且不会使用循环。

int count = line.length() - line.replace(".", "").length();

其他回答

迟早会有循环发生。对你来说,编写(非常简单的)循环要比使用split之类的东西简单得多,后者比你需要的功能强大得多。

无论如何要将循环封装在一个单独的方法中,例如。

public static int countOccurrences(String haystack, char needle)
{
    int count = 0;
    for (int i=0; i < haystack.length(); i++)
    {
        if (haystack.charAt(i) == needle)
        {
             count++;
        }
    }
    return count;
}

那么你不需要在你的主代码中有循环-但循环必须在那里的某个地方。

String s = "a.b.c.d";
int charCount = s.length() - s.replaceAll("\\.", "").length();

ReplaceAll(".")将替换所有字符。

PhiLho的解决方案使用ReplaceAll("[^.]",""),不需要转义,因为[. .]]表示字符“点”,而不是“任何字符”。

String s = "a.b.c.d";
long result = s.chars().filter(ch -> ch == '.').count();

试试下面的代码:

package com.java.test;

import java.util.HashMap;
import java.util.Map;

public class TestCuntstring {

    public static void main(String[] args) {

        String name = "Bissssmmayaa";
        char[] ar = new char[name.length()];
        for (int i = 0; i < name.length(); i++) {
            ar[i] = name.charAt(i);
        }
        Map<Character, String> map=new HashMap<Character, String>();
        for (int i = 0; i < ar.length; i++) {
            int count=0;
            for (int j = 0; j < ar.length; j++) {
                if(ar[i]==ar[j]){
                    count++;
                }
            }
            map.put(ar[i], count+" no of times");
        }
        System.out.println(map);
    }

}

一个更简单的解决方案是根据匹配的字符拆分字符串。

例如,

int getOccurences(字符串字符,字符串){ 字符串[]words = String .split(字符); 回来的话。长度- 1; }

这将在以下情况下返回4: getOccurences(“o”,“关于一只敏捷的棕色狐狸的事情”);