簡體   English   中英

計算字符串中字符的出現

[英]Count occurence of a character in a string

我試圖計算字符串中字母的出現,但是我用數字代替了它們,以使其更清晰。 然后當我運行該代碼時,它不會顯示我想要的結果。我真的不知道為什么...請幫助! 非常感謝!!

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

計算字符串中特定字符的一種相對簡短而整潔的方法是使用replaceAll方法的返回值:

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

模式[^x]x可以替換為任何char(或不同數量的char))將匹配給定String中 x 之外的所有內容。 因此, TEST [^T]將用給定的替換替換ES (為"" (無))並保留T 該方法將返回TT 如果計算該長度,您將收到給定字符串的搜索字符數。

這個例子

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

版畫

2
1
1

(請記住,方法區分大小寫)

使用像Hashmap這樣的集合。 此處,字符存儲遇到的每個唯一字符,整數存儲遇到的每個字符的計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM