我有字符串

a.b.c.d

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

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


当前回答

 public static int countSubstring(String subStr, String str) {

    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.substring(i).startsWith(subStr)) {
            count++;
        }
    }
    return count;
}

其他回答

完整的示例:

public class CharacterCounter
{

  public static int countOccurrences(String find, String string)
  {
    int count = 0;
    int indexOf = 0;

    while (indexOf > -1)
    {
      indexOf = string.indexOf(find, indexOf + 1);
      if (indexOf > -1)
        count++;
    }

    return count;
  }
}

电话:

int occurrences = CharacterCounter.countOccurrences("l", "Hello World.");
System.out.println(occurrences); // 3

好的,受Yonatan解决方案的启发,这里有一个纯递归的库方法-唯一使用的库方法是length()和charAt(),它们都不做任何循环:

public static int countOccurrences(String haystack, char needle)
{
    return countOccurrences(haystack, needle, 0);
}

private static int countOccurrences(String haystack, char needle, int index)
{
    if (index >= haystack.length())
    {
        return 0;
    }

    int contribution = haystack.charAt(index) == needle ? 1 : 0;
    return contribution + countOccurrences(haystack, needle, index+1);
}

递归是否算作循环取决于您使用的确切定义,但这可能是您能得到的最接近的定义。

我不知道现在大多数jvm是否都做尾递归…当然,如果不是这样,对于适当长的字符串就会出现同名堆栈溢出。

这里是最简单和容易理解的,不使用数组,只需使用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}

lambda一行代码 不需要外部库。 用每个字符的计数创建一个映射:

Map<Character,Long> counts = "a.b.c.d".codePoints().boxed().collect(
    groupingBy( t -> (char)(int)t, counting() ) );

获取:{a=1, b=1, c=1, d=1, .=3} 某一人物的数目。”。’已经结束了: 计数。('。”)

(出于病态的好奇心,我也写了一个lambda解,想知道我的解有多慢,最好是来自有10行解的人。)

一个简短的例子是

String text = "a.b.c.d";
int count = text.split("\\.",-1).length-1;