我有字符串

a.b.c.d

我想数一下'的出现次数。,最好是一句单句俏皮话。

(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。


当前回答

不确定这样做的效率,但这是我在不引入第三方库的情况下所能写的最短代码:

public static int numberOf(String target, String content)
{
    return (content.split(target).length - 1);
}

其他回答

如果你想数不。字符串'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

使用Java 8和HashMap,没有任何库来计数所有不同的字符:

private static void countChars(String string) {
    HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
    string.chars().forEach(letter -> hm.put(letter, (hm.containsKey(letter) ? hm.get(letter) : 0) + 1));
    hm.forEach((c, i) -> System.out.println(((char)c.intValue()) + ":" + i));
}

迟早会有循环发生。对你来说,编写(非常简单的)循环要比使用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;
}

那么你不需要在你的主代码中有循环-但循环必须在那里的某个地方。

好吧,在一个非常相似的任务中,我偶然发现了这个线程。 我没有看到任何编程语言的限制,因为groovy运行在java虚拟机上: 这里是我如何能够解决我的问题使用Groovy。

"a.b.c.".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;
}