我有一个字符串
(之前我曾表达过这个限制条件为“不使用循环”,以防你想知道为什么每个人都试图回答而不使用循环)。
a.b.c.d
我希望以惯用方式计算“.”的出现次数,最好是一行代码解决。(之前我曾表达过这个限制条件为“不使用循环”,以防你想知道为什么每个人都试图回答而不使用循环)。
a.b.c.d
我希望以惯用方式计算“.”的出现次数,最好是一行代码解决。split()
函数。int noOccurence=string.split("#",-1).length-1;
[0:"1";1:""; 2:"2"; 3:"3"]
),而不是大小为 9 的数组 ([0:"1"; 1:""; 2:"2"; 3:"3"; 4:""; 5:""; 6:""; 7:""; 8:""]
)。 - klaarpublic static int countOccurrences(String container, String content){
int lastIndex, currIndex = 0, occurrences = 0;
while(true) {
lastIndex = container.indexOf(content, currIndex);
if(lastIndex == -1) {
break;
}
currIndex = lastIndex + content.length();
occurrences++;
}
return occurrences;
}
import java.util.Scanner;
class apples {
public static void main(String args[]) {
Scanner bucky = new Scanner(System.in);
String hello = bucky.nextLine();
int charCount = hello.length() - hello.replaceAll("e", "").length();
System.out.println(charCount);
}
}// COUNTS NUMBER OF "e" CHAR´s within any string input
好的,我看到了一个相似的任务,然后发现这个线程。我没有看到任何编程语言的限制,而且由于Groovy在Java虚拟机上运行:
以下是我如何使用Groovy解决我的问题。
"a.b.c.".count(".")
Using Eclipse Collections
int count = Strings.asChars("a.b.c.d").count(c -> c == '.');
如果您需要计数多个字符,可以使用CharBag
操作如下:
CharBag bag = Strings.asChars("a.b.c.d").toBag();
int count = bag.occurrencesOf('.');
虽然方法可以隐藏它,但没有循环(或递归)就无法计数。出于性能考虑,您想使用char[]。
public static int count( final String s, final char c ) {
final char[] chars = s.toCharArray();
int count = 0;
for(int i=0; i<chars.length; i++) {
if (chars[i] == c) {
count++;
}
}
return count;
}
这是我用来计算字符串出现次数的方法。
希望有人会觉得有帮助。
private long countOccurrences(String occurrences, char findChar){
return occurrences.chars().filter( x -> {
return x == findChar;
}).count();
}
这是一种略微不同的递归解决方案:
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);
}
在代码中,某些地方需要循环。唯一的方法是完全展开循环:
int numDots = 0;
if (s.charAt(0) == '.') {
numDots++;
}
if (s.charAt(1) == '.') {
numDots++;
}
if (s.charAt(2) == '.') {
numDots++;
}
...等等,但是你需要手动在源代码编辑器中进行循环,而不是计算机运行它。看伪代码:
create a project
position = 0
while (not end of string) {
write check for character at position "position" (see above)
}
write code to output variable "numDots"
compile program
hand in homework
do not think of the loop that your "if"s may have been optimized and compiled to