【问题标题】:How to count how many times a letter appears in all of the strings of an array? [duplicate]如何计算一个字母在数组的所有字符串中出现的次数? [复制]
【发布时间】:2018-10-10 23:41:17
【问题描述】:
public static int countLetter(String[] x, String y){
    int count = 0;
    for(int i = 0; i < x.length; i++){
        for(int h = 0; h < x[i].length(); h++){
            String yo = new String(x[i].substring(h,h+1));
            if(yo==y){
                count++;}
            }
        }
        return count;
    }
}

我的方法应该返回一个整数,该整数计算字母在数组的所有字符串中出现的总次数。 (假设字符串是一个字母,我不能使用 charAt())。

【问题讨论】:

  • return (int)Arrays.stream(x).map(Pattern.compile(y, Pattern.LITERAL)::matcher).flatMap(Matcher::results).count();
  • return Stream.of(x).flatMap(s -&gt; s.chars().mapToObj(i -&gt; (char) i)).filter(s -&gt; s.equals(y.charAt(0))).count();
  • 绝对不需要new String(..) 子字符串(在Java 6 及更早版本中(可能还有早期Java 7 版本),但这个原因已不复存在)。

标签: java arrays string substring


【解决方案1】:

问题在于字符串比较。在 Java 中比较 2 个字符串时,您需要使用 equals()equalsIgnoreCase()

public static int countLetter(String[] x, String y) {
   int count = 0;
   for (int i = 0; i < x.length; i++) {
      for (int h = 0; h < x[i].length(); h++) {
         String yo = new String(x[i].substring(h, h + 1));
         if (yo.equals(y)) {
            count++;
         }
      }
   }
   return count;
}

您也可以使用char 代替String

public static int countLetter(String[] x, char y) {
   int count = 0;
   for (int i = 0; i < x.length; i++) {
      for (int h = 0; h < x[i].length(); h++) {
         if (x[i].charAt(h) == y) {
            count++;
         }
      }
   }
   return count;
}

【讨论】:

    【解决方案2】:

    这不是你比较字符串的方式。

    改变

    if(yo==y)

    if(yo.equals(y))
    

    或者如果你想忽略字母大小写

    if(yo.equalsIgnoreCase(y))
    

    【讨论】:

      【解决方案3】:

      您可以在第 6 行更改您的代码

      if(yo==y)
      

      if(yo.equals(y))
      

      这应该是可行的。

      【讨论】:

        猜你喜欢
        • 2021-08-04
        • 2015-12-01
        • 1970-01-01
        • 2014-05-26
        • 2013-11-04
        • 1970-01-01
        • 2020-07-23
        • 2016-01-23
        • 1970-01-01
        相关资源
        最近更新 更多