首页 > 解决方案 > 计算字符串列表中的笑脸

问题描述

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

笑脸的格式为:or;的眼睛、可选的鼻子-or~和嘴巴)or 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;
    }
}

标签: javastringlist

解决方案


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

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

}

推荐阅读