我有字符串

a.b.c.d

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

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


当前回答

使用Eclipse集合

int count = Strings.asChars("a.b.c.d").count(c -> c == '.');

如果你有一个以上的字符计数,你可以使用CharBag如下所示:

CharBag bag = Strings.asChars("a.b.c.d").toBag();
int count = bag.occurrencesOf('.');

注意:我是Eclipse Collections的提交者。

其他回答

虽然方法可以隐藏它,但没有循环(或递归)就无法计数。但出于性能考虑,您希望使用char[]。

public static int count( final String s, final char c ) {
  final char[] chars = s.toCharArray();
  int count = 0;
  for(int i=0; i<chars.length; i++) {
    if (chars[i] == c) {
      count++;
    }
  }
  return count;
}

使用replaceAll(即RE)听起来不是最好的方法。

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;
}

一个简短的例子是

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

下面的源代码会给你答案。在用户输入的单词中出现给定字符串的次数:-

import java.util.Scanner;

public class CountingOccurences {

    public static void main(String[] args) {

        Scanner inp= new Scanner(System.in);
        String str;
        char ch;
        int count=0;

        System.out.println("Enter the string:");
        str=inp.nextLine();

        while(str.length()>0)
        {
            ch=str.charAt(0);
            int i=0;

            while(str.charAt(i)==ch)
            {
                count =count+i;
                i++;
            }

            str.substring(count);
            System.out.println(ch);
            System.out.println(count);
        }

    }
}

可以在一行代码中使用split()函数

int noOccurence=string.split("#",-1).length-1;