2017-04-27 78 views
5

我試圖解決一個問題,我創建一個方法來計算某個字符串中大寫和小寫(「A」或「a」)的出現次數。我一直在研究這個問題一個星期,而我收到的主要錯誤是「char不能被解除引用」。任何人都可以指出我對這個Java問題的正確方向嗎?謝謝。計算一個java字符串中的特定事件的數量

class Main{ 
    public static int countA (String s) 
    { 
     String s1 = "a"; 
     String s2 = "A"; 
     int count = 0; 
     for (int i = 0; i < s.length; i++){ 
      String s3 = s.charAt(i); 
      if (s3.equals(s1) || s3.equals(s2)){ 
       count += 1; 
      } 
      else{ 
       System.out.print(""); 
      } 
     } 
    } 

    //test case below (dont change): 
    public static void main(String[] args){ 
     System.out.println(countA("aaA")); //3 
     System.out.println(countA("aaBBdf8k3AAadnklA")); //6 
    } 
} 
+0

第一個錯誤's.length',第二個錯誤'串S = s.charAt(I);' –

+0

你是什麼意思 「的第一個錯誤」。我應該怎樣改變它? @OusmaneMahyDiaw –

+0

第一次改變爲's.length()'爲第二次改變爲'String s3 = Character.toString(s.charAt(i));'。另一個很好的解決方案是由下面的@ScaryWombat提供的。 –

回答

4

嘗試一個簡單的解決方案

String in = "aaBBdf8k3AAadnklA"; 
String out = in.replace ("A", "").replace ("a", ""); 
int lenDiff = in.length() - out.length(); 

也如@克里斯提到在他的回答中,字符串可以轉換爲小寫,然後再只做單一的檢查

+0

這裏非常直觀的解決方案! –

3

計數數的時間'a''A'出現在字符串:

public int numberOfA(String s) { 
    s = s.toLowerCase(); 
    int sum = 0; 
    for(int i = 0; i < s.length(); i++){ 
     if(s.charAt(i) == 'a') 
      sum++; 
    } 
    return sum; 
} 

或者只是代替一切,看看你的字符串有多長:

int numberOfA = string.replaceAll("[^aA]", "").length(); 
4

,我收到的主要錯誤是「字符不能 取消引用」

改變這一點:

s.length // this syntax is incorrect 

這樣:

s.length() // this is how you invoke the length method on a string 

還,更改此:

String s3 = s.charAt(i); // you cannot assign a char type to string type 

這樣:

String s3 = Character.toString(s.charAt(i)); // convert the char to string 

另一種解決方案以簡單的方式完成你的任務是通過使用Stream#filter方法。然後將Stream內的每個String轉換爲小寫,然後進行比較,如果有任何字符串匹配"a"我們保留它,如果不是我們忽略它,最後,我們只需返回計數。

public static int countA(String input) 
{ 
    return (int)Arrays.stream(input.split("")).filter(s -> s.toLowerCase().equals("a")).count(); 
} 
1

要了解時代特徵一個一個出現在的數量。

int numA = string.replaceAll("[^aA]","").length(); 
相關問題