我正在尝试计算List
中给定的Strings
中出现笑脸的情况。
笑脸的格式为:
或;
,眼睛,可选的鼻子-
或~
以及嘴巴为)
或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;
}
}
答案 0 :(得分:1)
最好为此使用正则表达式。这个小代码使用regexp查找所有模式并报告计数:
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;
}
}
答案 1 :(得分:0)
最佳答案是使用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