我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
得到答案最简单的方法如下:
public static void main(String[] args) {
String string = "a.b.c.d";
String []splitArray = string.split("\\.",-1);
System.out.println("No of . chars is : " + (splitArray.length-1));
}
其他回答
我有一个类似于Mladen的想法,但恰恰相反……
String s = "a.b.c.d";
int charCount = s.replaceAll("[^.]", "").length();
println(charCount);
如果你想数不。字符串'SELENIUM'中的相同字符,或者你想打印字符串'SELENIUM'中的唯一字符。
public class Count_Characters_In_String{
public static void main(String []args){
String s = "SELENIUM";
System.out.println(s);
int counter;
String g = "";
for( int i=0; i<s.length(); i++ ) {
if(g.indexOf(s.charAt(i)) == - 1){
g=g+s.charAt(i);
}
}
System.out.println(g + " ");
for( int i=0; i<g.length(); i++ ) {
System.out.print(",");
System.out.print(s.charAt(i)+ " : ");
counter=0;
for( int j=0; j<s.length(); j++ ) {
if( g.charAt(i) == s.charAt(j) ) {
counter=counter+1;
}
}
System.out.print(counter);
}
}
}
/******************** 输出 **********************/
硒
铒
S: 1, e: 2, l: 1, e: 1, n: 1, i: 1, u: 1
在代码的某个地方,某些东西必须循环。解决这个问题的唯一方法是完全展开循环:
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
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
在java-8中,你也可以使用流来实现这一点。显然,在幕后有一个迭代,但您不必显式地编写它!
public static long countOccurences(String s, char c){
return s.chars().filter(ch -> ch == c).count();
}
countOccurences("a.b.c.d", '.'); //3
countOccurences("hello world", 'l'); //3