2015-02-06 113 views
0
public int count_chars_in_String(String s, String s1){ 
     int count = 0; 
     for(int i = 0; i<s.length();i++){ 
      if(s.charAt(i) = s1.charAt(i)){ 

      } 
     } 
    } 

這是我所能想到的,在if循環中是錯誤的。它說左手邊必須是一個變量。我怎麼能像計算第一個字符串和第二個字符串都出現的字符一樣?如何計算第一次字符串出現的次數字符串還有第二次字符串出現的次數?

+0

你是混亂的'='和''== 。無論如何,我可以用幾種方式來解釋這個問題,使其更清晰,請編輯它,幷包括輸入和預期輸出的例子,並解釋爲什麼這種輸出是正確的。 – Pshemo 2015-02-06 15:39:00

回答

1

您正在使用=運算符在您的if聲明中執行賦值。要比較兩個字符,請使用比較運算符:==

1

'='運算符是賦值。 '=='運算符在大多數語言中都是compraision運算符(相等)。

+0

就像一個SO FYI一樣,爲了突出您在大多數鍵盤上使用與波浪鍵匹配的嚴重口音 – Ascalonian 2015-02-06 15:40:35

0

首先在實現它之前瞭解它是如何工作的。下面的代碼將計算第二個字符串的char的出現次數,比較第一個字符串的字符的char。當第一個字符串具有相同的字符不止一次時,這將不是完美的。不要進行修改爲..

public int count_chars_in_String(String s, String s1){ 
    int count = 0; 
    for(int i = 0; i<s.length();i++){ 
     for(int j = 0,k = 0; j<s1.length();j++){ 
      if(s.charAt(i) == s1.charAt(j)){ 
       k + = 1; 
      } 
     } 
     System.out.println(s.charAt(i)+": "+k+" times"); 
    } 
} 
1

使用==來比較,也請確保您的代碼,S和S1的長度是相同的(或者你用最小的字符串作爲終端的長度),否則您將收到:

StringIndexOutOfBoundsException 

錯誤。

0

忽略你的問題的體(這在這個時間是有缺陷的),我會數同時出現在兩個字符串這樣的字符:

public Set<Character> asSet(String s) { 
    Set<Character> in = new HashSet<>(); 
    // Roll all of the strings characters into the set. 
    s.chars().forEach(c -> in.add((char) c)); 
    return in; 
} 

public int countCharsInBoth(String s, String s1) { 
    // All characters in the first string. 
    Set<Character> inBoth = asSet(s); 
    // Keep only those in the second string too. 
    inBoth.retainAll(asSet(s1)); 
    // Size of that set is count. 
    return inBoth.size(); 
} 

public void test() { 
    // Prints 3 as expected. 
    System.out.println(countCharsInBoth("Hello", "Hell")); 
} 
相關問題