java - 计算字符串列表中的笑脸
问题描述
我正在尝试计算给定的笑脸的出现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;
}
}
解决方案
最好为此使用正则表达式。这个小代码使用正则表达式来查找所有模式并报告计数:
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;
}
}
推荐阅读
- azure - 在 Azure Powershell 或云 shell 的两个存储帐户中创建 100 个容器
- python - Python Tkinter GUI 界面
- java - 使用 Spring MVC 控制器映射 JSP 文本输入
- python-2.7 - 使用 Python 2.7 下载损坏的 .jpg 文件
- php - 抓取网站动态内容 - 服务器端
- css - 如何在 Materialise CSS 中水平对齐列?
- postgresql - sqlalchemy 可以同时支持使用不同的模式吗?
- javascript - 如何限制输入元素中允许的字符集?
- bash - 采购外部 bash 脚本时 crontab 不工作
- ruby-on-rails - 如果验证符合 ruby on rails 模型,如何使提交按钮可以点击