繁体   English   中英

我如何计算在第一个字符串处出现char的次数在第二个字符串处也出现的次数?

[英]How can I count how many times char occur at first String also cccur at second String?

   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循环中这是错误的。 它说左侧必须是一个变量。 我该怎么做,比如计算同时出现在第一个字符串和第二个字符串上的字符?

您正在使用=运算符在if语句中执行赋值。 要比较两个字符,请使用比较运算符: ==

“ =”运算符是赋值。 在大多数语言中,“ ==”运算符是比较运算符(相等)。

使用==进行比较,并在代码中确保s和s1的长度相同(或使用最小字符串的长度作为终止符),否则将得到:

StringIndexOutOfBoundsException

错误。

首先,在实现之前了解它的工作原理。下面的代码将比较第二个字符串的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");
    }
}

忽略问题的主体(目前是有缺陷的),我会计算出现在两个字符串中的字符,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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