简体   繁体   English

计算字符串中字符的出现

[英]Count occurence of a character in a string

I tried to count the occurrence of alphabets in a string, but I substitue them with numbers to make it clearer. 我试图计算字符串中字母的出现,但是我用数字代替了它们,以使其更清晰。 Then when I run that code, it doesnt display the results I want.I dont really know why...Please help!! 然后当我运行该代码时,它不会显示我想要的结果。我真的不知道为什么...请帮助! Thank you so much!! 非常感谢!!

    Scanner Scanner1 = new Scanner(System.in);
    out.println("Please type in a string below.");
    String UserInput = Scanner1.nextLine();
    String Index = "12345";
    int length = 2;//Modified
    int[] count = new int[length];
    int length2 = 5; //Modified
    int n1 = 0;
    int n2 = 0;
    out.println(UserInput.charAt(n1));//Modified
    out.println(Index.charAt(n2));//Modified
    for (int i = 0; i < length; i++) {
        if (UserInput.charAt(n1) == Index.charAt(n2)) {
            n1++;
            count[length - (length - n1)]++;

        } else {
            n2++;
            if(n2==length2)
            {
                n2 = n2-length2;
            }
        }
    }

A relatively short and neat way to count a specific character in a string is using the return value of the replaceAll method: 计算字符串中特定字符的一种相对简短而整洁的方法是使用replaceAll方法的返回值:

public static int countChar(final String str, final char c) {
    return str.replaceAll("[^" + c + "]","").length();
}

The pattern [^x] ( x can be replaced with any char (or amount of different chars)) will match everything in a given String except x . 模式[^x]x可以替换为任何char(或不同数量的char))将匹配给定String中 x 之外的所有内容。 So [^T] of TEST would replace E and S with the given replacement (which is "" (nothing)) and keeps the T s. 因此, TEST [^T]将用给定的替换替换ES (为"" (无))并保留T The method would return TT . 该方法将返回TT If you count that length, you'll receive the count of the searched character of the given string. 如果计算该长度,您将收到给定字符串的搜索字符数。

The example 这个例子

System.out.println(countChar("TEST", 'T'));
System.out.println(countChar("TEST", 'E'));
System.out.println(countChar("TEST", 'S'));

prints 版画

2
1
1

(keep in mind that is method is case sensitive) (请记住,方法区分大小写)

use collections like Hashmap. 使用像Hashmap这样的集合。 Here Character stores every unique character encountered and Integer stores the count of every character whenever it is encountered. 此处,字符存储遇到的每个唯一字符,整数存储遇到的每个字符的计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM