我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
迟早会有循环发生。对你来说,编写(非常简单的)循环要比使用split之类的东西简单得多,后者比你需要的功能强大得多。
无论如何要将循环封装在一个单独的方法中,例如。
public static int countOccurrences(String haystack, char needle)
{
int count = 0;
for (int i=0; i < haystack.length(); i++)
{
if (haystack.charAt(i) == needle)
{
count++;
}
}
return count;
}
那么你不需要在你的主代码中有循环-但循环必须在那里的某个地方。
其他回答
我的“惯用的一句话”解决方案:
int count = "a.b.c.d".length() - "a.b.c.d".replace(".", "").length();
不知道为什么使用StringUtils的解决方案是可以接受的。
这是一个稍微不同风格的递归解决方案:
public static int countOccurrences(String haystack, char needle)
{
return countOccurrences(haystack, needle, 0);
}
private static int countOccurrences(String haystack, char needle, int accumulator)
{
if (haystack.length() == 0) return accumulator;
return countOccurrences(haystack.substring(1), needle, haystack.charAt(0) == needle ? accumulator + 1 : accumulator);
}
String[] parts = text.split(".");
int occurances = parts.length - 1;
" It's a great day at O.S.G. Dallas! "
-- Famous Last Words
好吧,这是一个了解Java的情况,特别是对Java中已经可用的集合类的基本理解。如果你看了整篇文章,除了斯蒂芬·霍金对宇宙起源的解释,达尔文关于进化论的平装书,以及吉恩·罗登贝瑞的《星际迷航》演员选择,他们为什么选择威廉·夏特纳,除了如何快速简单地做到这一点……
... 我还需要多说吗?
我有一个类似于Mladen的想法,但恰恰相反……
String s = "a.b.c.d";
int charCount = s.replaceAll("[^.]", "").length();
println(charCount);
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;
}