【问题标题】:Counting smileys in a List of strings计算字符串列表中的笑脸
【发布时间】:2018-07-20 16:28:47
【问题描述】:

我正在尝试计算Strings 的给定List 中笑脸的出现次数。

笑脸的格式为:; 用于眼睛,可选鼻子-~,以及)D 的嘴巴。

import java.util .*;

public class SmileFaces {

    public static int countSmileys(List<String> arrow) {

        int countF = 0;
        for (String x : arrow) {
            if (x.charAt(0) == ';' || x.charAt(0) == ':') {
                if (x.charAt(1) == '-' || x.charAt(1) == '~') {
                    if (x.charAt(2) == ')' || x.charAt(2) == 'D') {
                        countF++;

                    } else if (x.charAt(1) == ')' || x.charAt(1) == 'D') {
                        countF++;

                    }

                }

            }
        }
        return countF;
    }
}

【问题讨论】:

  • 你有问题还是只是在炫耀你的代码?
  • 请提供样本输入数据、期望结果和观察结果。
  • 如果字符串大小小于 3,这将抛出 IndexOutOfBoundsException;您可能需要为此添加一些验证。另外,也许你应该看看Pattern 类;它会更优雅地解决问题。
  • countSmileys(Collections.singletonList(""))
  • 对不起......它不工作......测试用例......预期结果得到结果

标签: java string list


【解决方案1】:

最好为此使用正则表达式。这个小代码使用正则表达式来查找所有模式并报告计数:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.List;
import java.util.Arrays;

// one class needs to have a main() method
public class Test
{

  private static final Pattern pattern = Pattern.compile("[:;][-~]?[)D]");

  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {

    List<String> arrow = Arrays.asList(":-) ;~D :) ;D", "sdgsfs :-)");

    System.out.println("found: " + countSmileys(arrow));

  }

    public static int countSmileys(List<String> arrow) {

      int count = 0;
      for (String x : arrow) {
          Matcher matcher = pattern.matcher(x);

          while(matcher.find()) {
              count++;
          }            
      }

      return count;
    }

}

【讨论】:

  • 我想投票,但 OP 从未真正提出过问题,所以我不知道这是否是一个有效的答案
  • 嘿,这是一个不错的方法...我不知道为什么我总是偏离正则表达式.....谢谢
  • 几乎所有字符串处理都最好使用 RegExp。除了 JSON 或 XML 等复杂的层次结构。
  • 谢谢.....今天晚上我要坐下来用正则表达式 - 回想一下,我记得几年前做过,以及它是如何变得不那么可怕的了解不多...感谢您的帮助...抱歉我的问题不清楚...很快就会掌握这个网站的窍门...已经离开太久了
  • 有很多在线正则表达式测试网站。你不需要 java 来测试它们。在 google 中搜索“regexp online”
【解决方案2】:

最佳答案是使用regex 表达式匹配。

但是因为你可以尝试的笑容很少:

@Test
public void countSmiles() {
    String smiles = ":),:-D,:~D,:~)";

    int count = StringUtils.countMatches(smiles,":)");
    count += StringUtils.countMatches(smiles,":D");
    count += StringUtils.countMatches(smiles,":-)");
    count += StringUtils.countMatches(smiles,":~)");
    count += StringUtils.countMatches(smiles,":-D");
    count += StringUtils.countMatches(smiles,":~D");
    System.out.println("count = " + count);
}

输出:

count = 4

【讨论】:

  • 可能要提一下,这是来自 Apache Commons Lang
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 2022-08-13
相关资源
最近更新 更多