2015-02-06 115 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")); 
} 
相关问题