我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
我有一个类似于Mladen的想法,但恰恰相反……
String s = "a.b.c.d";
int charCount = s.replaceAll("[^.]", "").length();
println(charCount);
其他回答
好吧,在一个非常相似的任务中,我偶然发现了这个线程。 我没有看到任何编程语言的限制,因为groovy运行在java虚拟机上: 这里是我如何能够解决我的问题使用Groovy。
"a.b.c.".count(".")
完成了。
我对此的“惯用语”是:
int count = StringUtils.countMatches("a.b.c.d", ".");
既然已经是通用语言了,为什么还要自己写呢?
Spring Framework的线性程序是:
int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");
public static void getCharacter(String str){
int count[]= new int[256];
for(int i=0;i<str.length(); i++){
count[str.charAt(i)]++;
}
System.out.println("The ascii values are:"+ Arrays.toString(count));
//Now display wht character is repeated how many times
for (int i = 0; i < count.length; i++) {
if (count[i] > 0)
System.out.println("Number of " + (char) i + ": " + count[i]);
}
}
}
如果你想数不。字符串'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
一个简短的例子是
String text = "a.b.c.d";
int count = text.split("\\.",-1).length-1;