简体   繁体   中英

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:

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 . So [^T] of TEST would replace E and S with the given replacement (which is "" (nothing)) and keeps the T s. The method would return 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. Here Character stores every unique character encountered and Integer stores the count of every character whenever it is encountered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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