我有字符串

a.b.c.d

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

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


当前回答

这就是我用来计算字符串出现次数的方法。

希望有人觉得有用。

    private long countOccurrences(String occurrences, char findChar){
        return  occurrences.chars().filter( x -> {
            return x == findChar;
        }).count();
    }

其他回答

public static int countOccurrences(String container, String content){
    int lastIndex, currIndex = 0, occurrences = 0;
    while(true) {
        lastIndex = container.indexOf(content, currIndex);
        if(lastIndex == -1) {
            break;
        }
        currIndex = lastIndex + content.length();
        occurrences++;
    }
    return occurrences;
}

这里是最简单和容易理解的,不使用数组,只需使用Hashmap。此外,它将计算空白,大写字符和小字符的数量,特殊字符等。

import java.util.HashMap;
  //The code by muralidharan  
    public class FindChars {
        
        public static void main(String[] args) {
            
            findchars("rererereerererererererere");
        }
        
        public static void findchars(String s){
            
            HashMap<Character,Integer> k=new HashMap<Character,Integer>();
            for(int i=0;i<s.length();i++){
                if(k.containsKey(s.charAt(i))){
                Integer v =k.get(s.charAt(i));
                k.put(s.charAt(i), v+1);
                }else{
                    k.put(s.charAt(i), 1);
                }
                
            }
            System.out.println(k);
            
        }
    
    }

O / P: {e = r = 12日13}

第二个输入:

findchars("The world is beautiful and $#$%%%%%%@@@@ is worst");

O / P: {@ = 4 = 7, = 2, b = 1, # = 1, d = 2, = 2美元,e = 2, % = 6 f = 1, h = 1, i = 3 l = 2, n = 1, o = 2, r = 2, = 3, T = 1, T = 2, u = 2, w = 2}

迟早会有循环发生。对你来说,编写(非常简单的)循环要比使用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";
long result = s.chars().filter(ch -> ch == '.').count();

下面是一个没有循环的解决方案:

public static int countOccurrences(String haystack, char needle, int i){
    return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}


System.out.println("num of dots is "+countOccurrences("a.b.c.d",'.',0));

嗯,有一个循环,但它是看不见的:-)

——约拿单