如何在字符串中计算字符出现的次数?

621
我有一个字符串
a.b.c.d
我希望以惯用方式计算“.”的出现次数,最好是一行代码解决。
(之前我曾表达过这个限制条件为“不使用循环”,以防你想知道为什么每个人都试图回答而不使用循环)。

1
作业?否则我看不出避免循环的要求。 - PhiLho
26
不是不喜欢使用循环,只是在寻找一个惯用语的一行代码。 - Bart
2
循环语句就是为了解决这样的问题而设计的,在通用工具类中编写循环,然后调用你刚创建的一行代码。 - che javara
字符串相关的类似问题:https://dev59.com/_HRA5IYBdhLWcg3w9ivq - koppor
显示剩余2条评论
48个回答

5
您可以在只有一行代码中使用split()函数。
int noOccurence=string.split("#",-1).length-1;

Split函数会创建字符串数组,这会消耗很多时间。 - Palec
你说得对,那是一个真正的问题。另一方面,它避免了在项目中引入第三方库(如果尚未完成)。这取决于你想做什么以及性能期望如何。 - Benj
3
这个解决方案不会包括末尾的空字符串,因为在调用这个重载的 split 方法时,参数 limit 被设置为零。例如:"1##2#3#####".split("#") 会产生一个大小为 4 的数组 ([0:"1";1:""; 2:"2"; 3:"3"]),而不是大小为 9 的数组 ([0:"1"; 1:""; 2:"2"; 3:"3"; 4:""; 5:""; 6:""; 7:""; 8:""])。 - klaar

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

3
import java.util.Scanner;

class apples {

    public static void main(String args[]) {    
        Scanner bucky = new Scanner(System.in);
        String hello = bucky.nextLine();
        int charCount = hello.length() - hello.replaceAll("e", "").length();
        System.out.println(charCount);
    }
}//      COUNTS NUMBER OF "e" CHAR´s within any string input

3

好的,我看到了一个相似的任务,然后发现这个线程。我没有看到任何编程语言的限制,而且由于Groovy在Java虚拟机上运行:

以下是我如何使用Groovy解决我的问题。

"a.b.c.".count(".")

完成。

3

Using Eclipse Collections

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的提交者。

3

虽然方法可以隐藏它,但没有循环(或递归)就无法计数。出于性能考虑,您想使用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)似乎不是最佳选择。

我认为这是最优雅的解决方案。你为什么使用 toCharArray 而不是直接使用 charAt? - Panayotis
循环使用charAt至少曾经较慢。这可能也取决于平台。真正找出差异的唯一方法是测量它们之间的区别。 - tcurdt

3

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

希望有人会觉得有帮助。

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

2
为什么不直接在字符上分割,然后获取结果数组的长度。数组长度总是实例数量加1。对吗?

2

这是一种略微不同的递归解决方案:

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

private static int countOccurrences(String haystack, char needle, int accumulator)
{
    if (haystack.length() == 0) return accumulator;
    return countOccurrences(haystack.substring(1), needle, haystack.charAt(0) == needle ? accumulator + 1 : accumulator);
}

2

在代码中,某些地方需要循环。唯一的方法是完全展开循环:

int numDots = 0;
if (s.charAt(0) == '.') {
    numDots++;
}

if (s.charAt(1) == '.') {
    numDots++;
}


if (s.charAt(2) == '.') {
    numDots++;
}

...等等,但是你需要手动在源代码编辑器中进行循环,而不是计算机运行它。看伪代码:

create a project
position = 0
while (not end of string) {
    write check for character at position "position" (see above)
}
write code to output variable "numDots"
compile program
hand in homework
do not think of the loop that your "if"s may have been optimized and compiled to

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接