我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
不确定这样做的效率,但这是我在不引入第三方库的情况下所能写的最短代码:
public static int numberOf(String target, String content)
{
return (content.split(target).length - 1);
}
其他回答
使用lambda函数删除所有字符进行计数 计数是前长度和后长度之差
String s = "a.b.c.d";
int count = s.length() - deleteChars.apply( s, "." ).length(); // 3
在这里找到deleteChars
如果你需要计算多个字符的出现次数,你可以一次性完成: 如。对于b c和。
int count = s.length() - deleteChars.apply( s, "bc." ).length(); // 5
我有一个类似于Mladen的想法,但恰恰相反……
String s = "a.b.c.d";
int charCount = s.replaceAll("[^.]", "").length();
println(charCount);
String s = "a.b.c.d";
long result = s.chars().filter(ch -> ch == '.').count();
public static int countSubstring(String subStr, String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.substring(i).startsWith(subStr)) {
count++;
}
}
return count;
}
我看到过很多这样的花招。现在我不反对漂亮的技巧,但就我个人而言,我喜欢简单地调用那些意味着要做工作的方法,所以我创造了另一个答案。
注意,如果性能有问题,请使用Jon Skeet的答案。在我看来,这个更一般化,因此可读性稍强(当然,对于字符串和模式也可重用)。
public static int countOccurances(char c, String input) {
return countOccurancesOfPattern(Pattern.quote(Character.toString(c)), input);
}
public static int countOccurances(String s, String input) {
return countOccurancesOfPattern(Pattern.quote(s), input);
}
public static int countOccurancesOfPattern(String pattern, String input) {
Matcher m = Pattern.compile(pattern).matcher(input);
int count = 0;
while (m.find()) {
count++;
}
return count;
}