How do I count the number of occurrences of a char in a String?











up vote
459
down vote

favorite
92












I have the string



a.b.c.d


I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.



(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).










share|improve this question




















  • 3




    why the loop aversion?
    – Blair Conrad
    Nov 9 '08 at 16:02






  • 1




    Homework? Because otherwise I don't see the requirement to avoid the loop.
    – PhiLho
    Nov 9 '08 at 16:13






  • 19




    Not averse to a loop so much as looking for an idiomatic one-liner.
    – Bart
    Nov 17 '08 at 14:28






  • 2




    Loops were made for a problem like this, write the loop in a common Utility class then call your freshly minted one liner.
    – che javara
    Sep 1 '15 at 21:31










  • Similar question for strings: stackoverflow.com/questions/767759/…
    – koppor
    Apr 16 '17 at 19:41















up vote
459
down vote

favorite
92












I have the string



a.b.c.d


I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.



(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).










share|improve this question




















  • 3




    why the loop aversion?
    – Blair Conrad
    Nov 9 '08 at 16:02






  • 1




    Homework? Because otherwise I don't see the requirement to avoid the loop.
    – PhiLho
    Nov 9 '08 at 16:13






  • 19




    Not averse to a loop so much as looking for an idiomatic one-liner.
    – Bart
    Nov 17 '08 at 14:28






  • 2




    Loops were made for a problem like this, write the loop in a common Utility class then call your freshly minted one liner.
    – che javara
    Sep 1 '15 at 21:31










  • Similar question for strings: stackoverflow.com/questions/767759/…
    – koppor
    Apr 16 '17 at 19:41













up vote
459
down vote

favorite
92









up vote
459
down vote

favorite
92






92





I have the string



a.b.c.d


I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.



(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).










share|improve this question















I have the string



a.b.c.d


I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.



(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).







java string






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 2 at 17:32









Ivar

2,661113040




2,661113040










asked Nov 9 '08 at 14:07









Bart

5,16652423




5,16652423








  • 3




    why the loop aversion?
    – Blair Conrad
    Nov 9 '08 at 16:02






  • 1




    Homework? Because otherwise I don't see the requirement to avoid the loop.
    – PhiLho
    Nov 9 '08 at 16:13






  • 19




    Not averse to a loop so much as looking for an idiomatic one-liner.
    – Bart
    Nov 17 '08 at 14:28






  • 2




    Loops were made for a problem like this, write the loop in a common Utility class then call your freshly minted one liner.
    – che javara
    Sep 1 '15 at 21:31










  • Similar question for strings: stackoverflow.com/questions/767759/…
    – koppor
    Apr 16 '17 at 19:41














  • 3




    why the loop aversion?
    – Blair Conrad
    Nov 9 '08 at 16:02






  • 1




    Homework? Because otherwise I don't see the requirement to avoid the loop.
    – PhiLho
    Nov 9 '08 at 16:13






  • 19




    Not averse to a loop so much as looking for an idiomatic one-liner.
    – Bart
    Nov 17 '08 at 14:28






  • 2




    Loops were made for a problem like this, write the loop in a common Utility class then call your freshly minted one liner.
    – che javara
    Sep 1 '15 at 21:31










  • Similar question for strings: stackoverflow.com/questions/767759/…
    – koppor
    Apr 16 '17 at 19:41








3




3




why the loop aversion?
– Blair Conrad
Nov 9 '08 at 16:02




why the loop aversion?
– Blair Conrad
Nov 9 '08 at 16:02




1




1




Homework? Because otherwise I don't see the requirement to avoid the loop.
– PhiLho
Nov 9 '08 at 16:13




Homework? Because otherwise I don't see the requirement to avoid the loop.
– PhiLho
Nov 9 '08 at 16:13




19




19




Not averse to a loop so much as looking for an idiomatic one-liner.
– Bart
Nov 17 '08 at 14:28




Not averse to a loop so much as looking for an idiomatic one-liner.
– Bart
Nov 17 '08 at 14:28




2




2




Loops were made for a problem like this, write the loop in a common Utility class then call your freshly minted one liner.
– che javara
Sep 1 '15 at 21:31




Loops were made for a problem like this, write the loop in a common Utility class then call your freshly minted one liner.
– che javara
Sep 1 '15 at 21:31












Similar question for strings: stackoverflow.com/questions/767759/…
– koppor
Apr 16 '17 at 19:41




Similar question for strings: stackoverflow.com/questions/767759/…
– koppor
Apr 16 '17 at 19:41












41 Answers
41






active

oldest

votes













1 2
next











up vote
646
down vote



accepted










My 'idiomatic one-liner' for this is:



int count = StringUtils.countMatches("a.b.c.d", ".");


Why write it yourself when it's already in commons lang?



Spring Framework's oneliner for this is:



int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");





share|improve this answer



















  • 2




    commons.apache.org/proper/commons-lang/download_lang.cgi
    – Jared Burrows
    Apr 20 '13 at 20:22






  • 39




    Guava equivalent: int count = CharMatcher.is('.').countIn("a.b.c.d"); ...As answered by dogbane in a duplicate question.
    – Jonik
    Aug 12 '13 at 17:00








  • 15




    Although i will not downvote this, it is (a) requiring 3rd party libs and (b) expensive.
    – javadba
    Jan 23 '14 at 21:24






  • 1




    if someone needs it: grepcode.com/file/repo1.maven.org/maven2/commons-lang/…
    – cV2
    Nov 27 '15 at 12:54








  • 14




    What's been expensive, at every company at which I've worked, is having lots of poorly-written and poorly-maintained "*Utils" classes. Part of your job is to know what's available in Apache Commons.
    – AbuNassar
    Oct 5 '16 at 14:58


















up vote
909
down vote













How about this. It doesn't use regexp underneath so should be faster than some of the other solutions and won't use a loop.



int count = line.length() - line.replace(".", "").length();





share|improve this answer

















  • 107




    Easiest way. Clever one. And it works on Android, where there is no StringUtils class
    – Jose_GD
    Nov 6 '12 at 13:12








  • 35




    This is the best answer. The reason it is the best is because you don't have to import another library.
    – Alex Spencer
    Jul 9 '13 at 20:03






  • 21




    Very practical but ugly as hell. I don't recommend it as it leads to confusing code.
    – Daniel San
    Mar 25 '14 at 22:54






  • 26




    Ugly code can be minimized by making it a method in your own "StringUtils" class. Then the ugly code is in exactly one spot, and everywhere else is nicely readable.
    – RonR
    Jun 5 '14 at 16:54






  • 22




    The loop method is much faster than this. Especially when wanting to count a char instead of a String (since there is no String.replace(char, char) method). On a 15 character string, I get a difference of 6049 ns vs 26,739 ns (averaged over 100runs). Raw numbers are huge difference, but percetage wise...it adds up. Avoid the memory allocations - use a loop!
    – Ben
    Nov 18 '14 at 15:41


















up vote
212
down vote













Summarize other answer and what I know all ways to do this using a one-liner:



   String testString = "a.b.c.d";


1) Using Apache Commons



int apache = StringUtils.countMatches(testString, ".");
System.out.println("apache = " + apache);


2) Using Spring Framework's



int spring = org.springframework.util.StringUtils.countOccurrencesOf(testString, ".");
System.out.println("spring = " + spring);


3) Using replace



int replace = testString.length() - testString.replace(".", "").length();
System.out.println("replace = " + replace);


4) Using replaceAll (case 1)



int replaceAll = testString.replaceAll("[^.]", "").length();
System.out.println("replaceAll = " + replaceAll);


5) Using replaceAll (case 2)



int replaceAllCase2 = testString.length() - testString.replaceAll("\.", "").length();
System.out.println("replaceAll (second case) = " + replaceAllCase2);


6) Using split



int split = testString.split("\.",-1).length-1;
System.out.println("split = " + split);


7) Using Java8 (case 1)



long java8 = testString.chars().filter(ch -> ch =='.').count();
System.out.println("java8 = " + java8);


8) Using Java8 (case 2), may be better for unicode than case 1



long java8Case2 = testString.codePoints().filter(ch -> ch =='.').count();
System.out.println("java8 (second case) = " + java8Case2);


9) Using StringTokenizer



int stringTokenizer = new StringTokenizer(" " +testString + " ", ".").countTokens()-1;
System.out.println("stringTokenizer = " + stringTokenizer);


From comment: Be carefull for the StringTokenizer, for a.b.c.d it will work but for a...b.c....d or ...a.b.c.d or a....b......c.....d... or etc. it will not work. It just will count for . between characters just once



More info in github



Perfomance test (using JMH, mode = AverageTime, score 0.010 better then 0.351):



Benchmark              Mode  Cnt  Score    Error  Units
1. countMatches avgt 5 0.010 ± 0.001 us/op
2. countOccurrencesOf avgt 5 0.010 ± 0.001 us/op
3. stringTokenizer avgt 5 0.028 ± 0.002 us/op
4. java8_1 avgt 5 0.077 ± 0.005 us/op
5. java8_2 avgt 5 0.078 ± 0.003 us/op
6. split avgt 5 0.137 ± 0.009 us/op
7. replaceAll_2 avgt 5 0.302 ± 0.047 us/op
8. replace avgt 5 0.303 ± 0.034 us/op
9. replaceAll_1 avgt 5 0.351 ± 0.045 us/op





share|improve this answer























  • Pt.6 works perfectly
    – vikramvi
    Dec 13 '16 at 14:35






  • 3




    Could you add Guava?
    – koppor
    Apr 16 '17 at 19:44










  • The printed strings do not match the ones above, and the order is fastest first which makes lookup tricky at least. Nice answer otherways!
    – Maarten Bodewes
    Jun 1 '17 at 11:05










  • case 2, generalized for codepoints that need more than one UTF-16 code unit: "1🚲2🚲3 has 2".codePoints().filter((c) -> c == "🚲".codePointAt(0)).count()
    – Tom Blodget
    Aug 1 at 22:50


















up vote
167
down vote













Sooner or later, something has to loop. It's far simpler for you to write the (very simple) loop than to use something like split which is much more powerful than you need.



By all means encapsulate the loop in a separate method, e.g.



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;
}


Then you don't need have the loop in your main code - but the loop has to be there somewhere.






share|improve this answer

















  • 4




    for (int i=0,l=haystack.length(); i < l; i++) be kind to your stack
    – Chris
    Nov 29 '09 at 13:43






  • 12




    (I'm not even sure where the "stack" bit of the comment comes from. It's not like this answer is my recursive one, which is indeed nasty to the stack.)
    – Jon Skeet
    Nov 29 '09 at 14:51






  • 2




    not only that but this is possibly an anti optimization without taking a look at what the jit does. If you did the above on an array for loop for example you might make things worse.
    – ShuggyCoUk
    Nov 30 '09 at 11:15






  • 3




    @sulai: Chris's concern is baseless, IMO, in the face of a trivial JIT optimization. Is there any reason that comment drew your attention at the moment, over three years later? Just interested.
    – Jon Skeet
    Jun 12 '14 at 13:39






  • 1




    Probably @sulai just came across the question as I did (while wondering if Java had a built-in method for this) and didn't notice the dates. However, I'm curious how moving the length() call outside of the loop could make performance worse, as mentioned by @ShuggyCoUk a few comments up.
    – JKillian
    Jul 30 '14 at 2:19


















up vote
60
down vote













I had an idea similar to Mladen, but the opposite...



String s = "a.b.c.d";
int charCount = s.replaceAll("[^.]", "").length();
println(charCount);





share|improve this answer























  • Correct. ReplaceAll(".") would replace any character, not just dot. ReplaceAll("\.") would have worked. Your solution is more straightforward.
    – VonC
    Nov 9 '08 at 16:20










  • jjnguy had actually suggested a replaceAll("[^.]") first, upon seeing my "a.b.c.d".split("\.").length-1 solution. But after being hit 5 times, I deleted my answer (and his comment).
    – VonC
    Nov 9 '08 at 16:24










  • "...now you have two problems" (oblig.) Anyway, I'd bet that there are tens of loops executing in replaceAll() and length(). Well, if it's not visible, it doesn't exist ;o)
    – Piskvor
    Aug 25 '10 at 11:22






  • 2




    i don't think it's a good idea to use regex and create a new string for the counting. i would just create a static method that loop every character in the string to count the number.
    – mingfai
    Apr 23 '11 at 23:14






  • 1




    @mingfai: indeed, but the original question is about making a one-liner, and even, without a loop (you can do a loop in one line, but it will be ugly!). Question the question, not the answer... :-)
    – PhiLho
    Apr 26 '11 at 17:25


















up vote
35
down vote













String s = "a.b.c.d";
int charCount = s.length() - s.replaceAll("\.", "").length();


ReplaceAll(".") would replace all characters.



PhiLho's solution uses ReplaceAll("[^.]",""), which does not need to be escaped, since [.] represents the character 'dot', not 'any character'.






share|improve this answer























  • I like this one. There's still a loop there, of course, as there has to be.
    – The Archetypal Paul
    Nov 9 '08 at 15:13










  • Untested, eh? :-)
    – PhiLho
    Nov 9 '08 at 16:14










  • PhiLho's solution is better
    – VonC
    Nov 9 '08 at 16:31










  • NB that you'd need to divide this number if you wanted to look for substrings of length > 1
    – rogerdpack
    Apr 3 '12 at 23:11


















up vote
26
down vote













My 'idiomatic one-liner' solution:



int count = "a.b.c.d".length() - "a.b.c.d".replace(".", "").length();


Have no idea why a solution that uses StringUtils is accepted.






share|improve this answer

















  • 3




    There is an older solution similar to this one in this post.
    – JCalcines
    Feb 5 '14 at 9:24








  • 6




    Because this solution is really inefficient
    – András
    May 14 '15 at 9:41










  • This creates an extra string just to produce a count. No idea why anyone would prefer this over StringUtils if StringUtils is an option. If it's not an option, they should just create a simple for loop in a utility class.
    – crush
    May 28 '16 at 20:15


















up vote
24
down vote













String s = "a.b.c.d";
long result = s.chars().filter(ch -> ch == '.').count();





share|improve this answer



















  • 1




    Vote + for a native solution.
    – Scadge
    Mar 23 '16 at 13:31


















up vote
21
down vote













A shorter example is



String text = "a.b.c.d";
int count = text.split("\.",-1).length-1;





share|improve this answer

















  • 2




    This one seems to have a relatively large overhead, be warned that it may create a lot of small strings. Normally that does not matter much but use with care.
    – Maarten Bodewes
    Aug 30 '14 at 16:51


















up vote
17
down vote













here is a solution without a loop:



public static int countOccurrences(String haystack, char needle, int i){
return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}


System.out.println("num of dots is "+countOccurrences("a.b.c.d",'.',0));


well, there is a loop, but it is invisible :-)



-- Yonatan






share|improve this answer

















  • 2




    Unless your string is so long you get an OutOfMemoryError.
    – Spencer Kormos
    Nov 9 '08 at 15:50










  • The problem sounds contrived enough to be homework, and if so, this recursion is probably the answer you're being asked to find.
    – erickson
    Nov 9 '08 at 17:43










  • That uses indexOf, which will loop... but a nice idea. Posting a truly "just recursive" solution in a minute...
    – Jon Skeet
    Nov 9 '08 at 18:03






  • 1




    LOL, so unnecessary.
    – Bernard Igiri
    Feb 16 '11 at 17:04










  • If it has more occurrences that your available stack slots, you will have a stack overflow exception ;)
    – Luca C.
    Jun 2 '14 at 16:19




















up vote
13
down vote













I don't like the idea of allocating a new string for this purpose. And as the string already has a char array in the back where it stores it's value, String.charAt() is practically free.



for(int i=0;i<s.length();num+=(s.charAt(i++)==delim?1:0))


does the trick, without additional allocations that need collection, in 1 line or less, with only J2SE.






share|improve this answer























  • Giving some love for this one because it is the only one doing a single pass over the string. I DO care about performance .
    – javadba
    Jan 22 '14 at 20:19










  • Why does this answer has so few votes? Seems to be the best to me.
    – Pascal
    May 26 '14 at 11:18








  • 1




    charAt iterates through 16 bit code points not characters! A char in Java is not a character. So this answer implies that there must be no Unicode symbol with a high surrogate being equal to the code point of delim. I am not sure if it is correct for the dot, but in general it might be not correct.
    – ceving
    Jul 22 '14 at 17:25




















up vote
12
down vote













Okay, inspired by Yonatan's solution, here's one which is purely recursive - the only library methods used are length() and charAt(), neither of which do any looping:



public static int countOccurrences(String haystack, char needle)
{
return countOccurrences(haystack, needle, 0);
}

private static int countOccurrences(String haystack, char needle, int index)
{
if (index >= haystack.length())
{
return 0;
}

int contribution = haystack.charAt(index) == needle ? 1 : 0;
return contribution + countOccurrences(haystack, needle, index+1);
}


Whether recursion counts as looping depends on which exact definition you use, but it's probably as close as you'll get.



I don't know whether most JVMs do tail-recursion these days... if not you'll get the eponymous stack overflow for suitably long strings, of course.






share|improve this answer























  • No, tail recursion will probably be in Java 7, but it's not widespread yet. This simple, direct tail recursion could be translated to a loop at compile time, but the Java 7 stuff is actually built-in to the JVM to handle chaining through different methods.
    – erickson
    Nov 10 '08 at 20:11






  • 3




    You'd be more likely to get tail recursion if your method returned a call to itself (including a running total parameter), rather than returning the result of performing an addition.
    – Stephen Denne
    Mar 20 '09 at 10:56


















up vote
11
down vote













Inspired by Jon Skeet, a non-loop version that wont blow your stack. Also useful starting point if you want to use the fork-join framework.



public static int countOccurrences(CharSequeunce haystack, char needle) {
return countOccurrences(haystack, needle, 0, haystack.length);
}

// Alternatively String.substring/subsequence use to be relatively efficient
// on most Java library implementations, but isn't any more [2013].
private static int countOccurrences(
CharSequence haystack, char needle, int start, int end
) {
if (start == end) {
return 0;
} else if (start+1 == end) {
return haystack.charAt(start) == needle ? 1 : 0;
} else {
int mid = (end+start)>>>1; // Watch for integer overflow...
return
countOccurrences(haystack, needle, start, mid) +
countOccurrences(haystack, needle, mid, end);
}
}


(Disclaimer: Not tested, not compiled, not sensible.)



Perhaps the best (single-threaded, no surrogate-pair support) way to write it:



public static int countOccurrences(String haystack, char needle) {
int count = 0;
for (char c : haystack.toCharArray()) {
if (c == needle) {
++count;
}
}
return count;
}





share|improve this answer






























    up vote
    9
    down vote













    Not sure about the efficiency of this, but it's the shortest code I could write without bringing in 3rd party libs:



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





    share|improve this answer



















    • 4




      To also count occurences at the end of the string you will have to call split with a negative limit argument like this: return (content.split(target, -1).length - 1);. By default occurences at the end of the string are omitted in the Array resulting from split(). See the Doku
      – vlz
      May 4 '14 at 12:08




















    up vote
    9
    down vote













    With java-8 you could also use streams to achieve this. Obviously there is an iteration behind the scenes, but you don't have to write it explicitly!



    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





    share|improve this answer





















    • Using .codePoints() instead of .chars() would then support any Unicode value (including those requiring surrogate pairs)
      – Luke Usherwood
      Aug 14 '14 at 14:40


















    up vote
    7
    down vote













    Complete sample:



    public class CharacterCounter
    {

    public static int countOccurrences(String find, String string)
    {
    int count = 0;
    int indexOf = 0;

    while (indexOf > -1)
    {
    indexOf = string.indexOf(find, indexOf + 1);
    if (indexOf > -1)
    count++;
    }

    return count;
    }
    }


    Call:



    int occurrences = CharacterCounter.countOccurrences("l", "Hello World.");
    System.out.println(occurrences); // 3





    share|improve this answer





















    • wrong code its not working when i try int occurrences = CharacterCounter.countOccurrences("1", "101"); System.out.println(occurrences); // 1
      – jayesh
      Jan 20 '14 at 6:32












    • I commit a fix for the code that works with the same logic
      – MaanooAk
      Jul 27 '17 at 7:06


















    up vote
    5
    down vote













    In case you're using Spring framework, you might also use "StringUtils" class.
    The method would be "countOccurrencesOf".






    share|improve this answer






























      up vote
      5
      down vote













      The simplest way to get the answer is as follow:



      public static void main(String args) {
      String string = "a.b.c.d";
      String splitArray = string.split("\.");
      System.out.println("No of . chars is : " + splitArray.length-1);
      }





      share|improve this answer





















      • This snippet does not return the correct amount of dots for a given input "a.b.c."
        – dekaru
        Nov 6 at 23:09










      • @dekaru Could you please paste your sting in the comment so that we can take a look.
        – Amar Magar
        Nov 14 at 7:19


















      up vote
      5
      down vote













      Also possible to use reduce in Java 8 to solve this problem:



      int res = "abdsd3$asda$asasdd$sadas".chars().reduce(0, (a, c) -> a + (c == '$' ? 1 : 0));
      System.out.println(res);


      Output:



      3





      share|improve this answer




























        up vote
        4
        down vote













        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





        share|improve this answer























        • This answer is essentially the same as stackoverflow.com/a/275979/577167
          – Joulukuusi
          Nov 14 '12 at 23:34


















        up vote
        4
        down vote













        You can use the split() function in just one line code



        int noOccurence=string.split("#").length-1;





        share|improve this answer























        • Split really creates the array of strings, which consumes much time.
          – Palec
          May 19 '16 at 17:03










        • You're right, that's a true concern. In another way it avoids bringing a third-party lib in your project (if not yet done). It depends on what you want to do and what is the performance expectation.
          – Benj
          Jun 14 '16 at 7:23






        • 2




          This solution will NOT include the trailing empty hits, because the argument limit is set to zero in this overloaded split method call. An example: "1##2#3#####".split("#") will only yield an array of size 4 ([0:"1";1:""; 2:"2"; 3:"3"]) instead size 9 ([0:"1"; 1:""; 2:"2"; 3:"3"; 4:""; 5:""; 6:""; 7:""; 8:""]).
          – klaar
          Aug 31 '16 at 15:05




















        up vote
        3
        down vote













        While methods can hide it, there is no way to count without a loop (or recursion). You want to use a char for performance reasons though.



        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;
        }


        Using replaceAll (that is RE) does not sound like the best way to go.






        share|improve this answer





















        • I think this is the most elegant solution. Why did you use toCharArray and not charAt directly?
          – Panayotis
          May 31 '17 at 8:29












        • Looping with charAt at least used to be slower. Might depend on the platform, too. The only way to really find out would be to measure the difference.
          – tcurdt
          May 31 '17 at 14:00


















        up vote
        3
        down vote













        public 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;
        }





        share|improve this answer




























          up vote
          2
          down vote













          Somewhere in the code, something has to loop. The only way around this is a complete unrolling of the loop:



          int numDots = 0;
          if (s.charAt(0) == '.') {
          numDots++;
          }

          if (s.charAt(1) == '.') {
          numDots++;
          }


          if (s.charAt(2) == '.') {
          numDots++;
          }


          ...etc, but then you're the one doing the loop, manually, in the source editor - instead of the computer that will run it. See the pseudocode:



          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





          share|improve this answer




























            up vote
            2
            down vote













            Here is a slightly different style recursion solution:



            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);
            }





            share|improve this answer




























              up vote
              2
              down vote













              Why not just split on the character and then get the length of the resulting array. array length will always be number of instances + 1. Right?






              share|improve this answer




























                up vote
                2
                down vote













                The following source code will give you no.of occurrences of a given string in a word entered by user :-



                import java.util.Scanner;

                public class CountingOccurences {

                public static void main(String args) {

                Scanner inp= new Scanner(System.in);
                String str;
                char ch;
                int count=0;

                System.out.println("Enter the string:");
                str=inp.nextLine();

                while(str.length()>0)
                {
                ch=str.charAt(0);
                int i=0;

                while(str.charAt(i)==ch)
                {
                count =count+i;
                i++;
                }

                str.substring(count);
                System.out.println(ch);
                System.out.println(count);
                }

                }
                }





                share|improve this answer






























                  up vote
                  2
                  down vote













                  int count = (line.length() - line.replace("str", "").length())/"str".length();





                  share|improve this answer






























                    up vote
                    2
                    down vote













                    Using Eclipse Collections



                    int count = CharAdapter.adapt("a.b.c.d").count(c -> c == '.');


                    If you have more than one character to count, you can use a CharBag as follows:



                    CharBag bag = CharAdapter.adapt("a.b.c.d").toBag();
                    int count = bag.occurrencesOf('.');


                    Note: I am a committer for Eclipse Collections.






                    share|improve this answer




























                      up vote
                      2
                      down vote













                      Well, with a quite similar task I stumbled upon this Thread.
                      I did not see any programming language restriction and since groovy runs on a java vm:
                      Here is how I was able to solve my Problem using Groovy.



                      "a.b.c.".count(".")


                      done.






                      share|improve this answer



























                        1 2
                        next



                        Your Answer






                        StackExchange.ifUsing("editor", function () {
                        StackExchange.using("externalEditor", function () {
                        StackExchange.using("snippets", function () {
                        StackExchange.snippets.init();
                        });
                        });
                        }, "code-snippets");

                        StackExchange.ready(function() {
                        var channelOptions = {
                        tags: "".split(" "),
                        id: "1"
                        };
                        initTagRenderer("".split(" "), "".split(" "), channelOptions);

                        StackExchange.using("externalEditor", function() {
                        // Have to fire editor after snippets, if snippets enabled
                        if (StackExchange.settings.snippets.snippetsEnabled) {
                        StackExchange.using("snippets", function() {
                        createEditor();
                        });
                        }
                        else {
                        createEditor();
                        }
                        });

                        function createEditor() {
                        StackExchange.prepareEditor({
                        heartbeatType: 'answer',
                        convertImagesToLinks: true,
                        noModals: true,
                        showLowRepImageUploadWarning: true,
                        reputationToPostImages: 10,
                        bindNavPrevention: true,
                        postfix: "",
                        imageUploader: {
                        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                        allowUrls: true
                        },
                        onDemand: false,
                        discardSelector: ".discard-answer"
                        ,immediatelyShowMarkdownHelp:true
                        });


                        }
                        });














                        draft saved

                        draft discarded


















                        StackExchange.ready(
                        function () {
                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f275944%2fhow-do-i-count-the-number-of-occurrences-of-a-char-in-a-string%23new-answer', 'question_page');
                        }
                        );

                        Post as a guest















                        Required, but never shown




















                        StackExchange.ready(function () {
                        $("#show-editor-button input, #show-editor-button button").click(function () {
                        var showEditor = function() {
                        $("#show-editor-button").hide();
                        $("#post-form").removeClass("dno");
                        StackExchange.editor.finallyInit();
                        };

                        var useFancy = $(this).data('confirm-use-fancy');
                        if(useFancy == 'True') {
                        var popupTitle = $(this).data('confirm-fancy-title');
                        var popupBody = $(this).data('confirm-fancy-body');
                        var popupAccept = $(this).data('confirm-fancy-accept-button');

                        $(this).loadPopup({
                        url: '/post/self-answer-popup',
                        loaded: function(popup) {
                        var pTitle = $(popup).find('h2');
                        var pBody = $(popup).find('.popup-body');
                        var pSubmit = $(popup).find('.popup-submit');

                        pTitle.text(popupTitle);
                        pBody.html(popupBody);
                        pSubmit.val(popupAccept).click(showEditor);
                        }
                        })
                        } else{
                        var confirmText = $(this).data('confirm-text');
                        if (confirmText ? confirm(confirmText) : true) {
                        showEditor();
                        }
                        }
                        });
                        });






                        41 Answers
                        41






                        active

                        oldest

                        votes








                        41 Answers
                        41






                        active

                        oldest

                        votes









                        active

                        oldest

                        votes






                        active

                        oldest

                        votes








                        1 2
                        next









                        up vote
                        646
                        down vote



                        accepted










                        My 'idiomatic one-liner' for this is:



                        int count = StringUtils.countMatches("a.b.c.d", ".");


                        Why write it yourself when it's already in commons lang?



                        Spring Framework's oneliner for this is:



                        int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");





                        share|improve this answer



















                        • 2




                          commons.apache.org/proper/commons-lang/download_lang.cgi
                          – Jared Burrows
                          Apr 20 '13 at 20:22






                        • 39




                          Guava equivalent: int count = CharMatcher.is('.').countIn("a.b.c.d"); ...As answered by dogbane in a duplicate question.
                          – Jonik
                          Aug 12 '13 at 17:00








                        • 15




                          Although i will not downvote this, it is (a) requiring 3rd party libs and (b) expensive.
                          – javadba
                          Jan 23 '14 at 21:24






                        • 1




                          if someone needs it: grepcode.com/file/repo1.maven.org/maven2/commons-lang/…
                          – cV2
                          Nov 27 '15 at 12:54








                        • 14




                          What's been expensive, at every company at which I've worked, is having lots of poorly-written and poorly-maintained "*Utils" classes. Part of your job is to know what's available in Apache Commons.
                          – AbuNassar
                          Oct 5 '16 at 14:58















                        up vote
                        646
                        down vote



                        accepted










                        My 'idiomatic one-liner' for this is:



                        int count = StringUtils.countMatches("a.b.c.d", ".");


                        Why write it yourself when it's already in commons lang?



                        Spring Framework's oneliner for this is:



                        int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");





                        share|improve this answer



















                        • 2




                          commons.apache.org/proper/commons-lang/download_lang.cgi
                          – Jared Burrows
                          Apr 20 '13 at 20:22






                        • 39




                          Guava equivalent: int count = CharMatcher.is('.').countIn("a.b.c.d"); ...As answered by dogbane in a duplicate question.
                          – Jonik
                          Aug 12 '13 at 17:00








                        • 15




                          Although i will not downvote this, it is (a) requiring 3rd party libs and (b) expensive.
                          – javadba
                          Jan 23 '14 at 21:24






                        • 1




                          if someone needs it: grepcode.com/file/repo1.maven.org/maven2/commons-lang/…
                          – cV2
                          Nov 27 '15 at 12:54








                        • 14




                          What's been expensive, at every company at which I've worked, is having lots of poorly-written and poorly-maintained "*Utils" classes. Part of your job is to know what's available in Apache Commons.
                          – AbuNassar
                          Oct 5 '16 at 14:58













                        up vote
                        646
                        down vote



                        accepted







                        up vote
                        646
                        down vote



                        accepted






                        My 'idiomatic one-liner' for this is:



                        int count = StringUtils.countMatches("a.b.c.d", ".");


                        Why write it yourself when it's already in commons lang?



                        Spring Framework's oneliner for this is:



                        int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");





                        share|improve this answer














                        My 'idiomatic one-liner' for this is:



                        int count = StringUtils.countMatches("a.b.c.d", ".");


                        Why write it yourself when it's already in commons lang?



                        Spring Framework's oneliner for this is:



                        int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Sep 21 '11 at 13:37









                        razeeth

                        62




                        62










                        answered Nov 29 '09 at 22:23









                        Cowan

                        31.7k95862




                        31.7k95862








                        • 2




                          commons.apache.org/proper/commons-lang/download_lang.cgi
                          – Jared Burrows
                          Apr 20 '13 at 20:22






                        • 39




                          Guava equivalent: int count = CharMatcher.is('.').countIn("a.b.c.d"); ...As answered by dogbane in a duplicate question.
                          – Jonik
                          Aug 12 '13 at 17:00








                        • 15




                          Although i will not downvote this, it is (a) requiring 3rd party libs and (b) expensive.
                          – javadba
                          Jan 23 '14 at 21:24






                        • 1




                          if someone needs it: grepcode.com/file/repo1.maven.org/maven2/commons-lang/…
                          – cV2
                          Nov 27 '15 at 12:54








                        • 14




                          What's been expensive, at every company at which I've worked, is having lots of poorly-written and poorly-maintained "*Utils" classes. Part of your job is to know what's available in Apache Commons.
                          – AbuNassar
                          Oct 5 '16 at 14:58














                        • 2




                          commons.apache.org/proper/commons-lang/download_lang.cgi
                          – Jared Burrows
                          Apr 20 '13 at 20:22






                        • 39




                          Guava equivalent: int count = CharMatcher.is('.').countIn("a.b.c.d"); ...As answered by dogbane in a duplicate question.
                          – Jonik
                          Aug 12 '13 at 17:00








                        • 15




                          Although i will not downvote this, it is (a) requiring 3rd party libs and (b) expensive.
                          – javadba
                          Jan 23 '14 at 21:24






                        • 1




                          if someone needs it: grepcode.com/file/repo1.maven.org/maven2/commons-lang/…
                          – cV2
                          Nov 27 '15 at 12:54








                        • 14




                          What's been expensive, at every company at which I've worked, is having lots of poorly-written and poorly-maintained "*Utils" classes. Part of your job is to know what's available in Apache Commons.
                          – AbuNassar
                          Oct 5 '16 at 14:58








                        2




                        2




                        commons.apache.org/proper/commons-lang/download_lang.cgi
                        – Jared Burrows
                        Apr 20 '13 at 20:22




                        commons.apache.org/proper/commons-lang/download_lang.cgi
                        – Jared Burrows
                        Apr 20 '13 at 20:22




                        39




                        39




                        Guava equivalent: int count = CharMatcher.is('.').countIn("a.b.c.d"); ...As answered by dogbane in a duplicate question.
                        – Jonik
                        Aug 12 '13 at 17:00






                        Guava equivalent: int count = CharMatcher.is('.').countIn("a.b.c.d"); ...As answered by dogbane in a duplicate question.
                        – Jonik
                        Aug 12 '13 at 17:00






                        15




                        15




                        Although i will not downvote this, it is (a) requiring 3rd party libs and (b) expensive.
                        – javadba
                        Jan 23 '14 at 21:24




                        Although i will not downvote this, it is (a) requiring 3rd party libs and (b) expensive.
                        – javadba
                        Jan 23 '14 at 21:24




                        1




                        1




                        if someone needs it: grepcode.com/file/repo1.maven.org/maven2/commons-lang/…
                        – cV2
                        Nov 27 '15 at 12:54






                        if someone needs it: grepcode.com/file/repo1.maven.org/maven2/commons-lang/…
                        – cV2
                        Nov 27 '15 at 12:54






                        14




                        14




                        What's been expensive, at every company at which I've worked, is having lots of poorly-written and poorly-maintained "*Utils" classes. Part of your job is to know what's available in Apache Commons.
                        – AbuNassar
                        Oct 5 '16 at 14:58




                        What's been expensive, at every company at which I've worked, is having lots of poorly-written and poorly-maintained "*Utils" classes. Part of your job is to know what's available in Apache Commons.
                        – AbuNassar
                        Oct 5 '16 at 14:58












                        up vote
                        909
                        down vote













                        How about this. It doesn't use regexp underneath so should be faster than some of the other solutions and won't use a loop.



                        int count = line.length() - line.replace(".", "").length();





                        share|improve this answer

















                        • 107




                          Easiest way. Clever one. And it works on Android, where there is no StringUtils class
                          – Jose_GD
                          Nov 6 '12 at 13:12








                        • 35




                          This is the best answer. The reason it is the best is because you don't have to import another library.
                          – Alex Spencer
                          Jul 9 '13 at 20:03






                        • 21




                          Very practical but ugly as hell. I don't recommend it as it leads to confusing code.
                          – Daniel San
                          Mar 25 '14 at 22:54






                        • 26




                          Ugly code can be minimized by making it a method in your own "StringUtils" class. Then the ugly code is in exactly one spot, and everywhere else is nicely readable.
                          – RonR
                          Jun 5 '14 at 16:54






                        • 22




                          The loop method is much faster than this. Especially when wanting to count a char instead of a String (since there is no String.replace(char, char) method). On a 15 character string, I get a difference of 6049 ns vs 26,739 ns (averaged over 100runs). Raw numbers are huge difference, but percetage wise...it adds up. Avoid the memory allocations - use a loop!
                          – Ben
                          Nov 18 '14 at 15:41















                        up vote
                        909
                        down vote













                        How about this. It doesn't use regexp underneath so should be faster than some of the other solutions and won't use a loop.



                        int count = line.length() - line.replace(".", "").length();





                        share|improve this answer

















                        • 107




                          Easiest way. Clever one. And it works on Android, where there is no StringUtils class
                          – Jose_GD
                          Nov 6 '12 at 13:12








                        • 35




                          This is the best answer. The reason it is the best is because you don't have to import another library.
                          – Alex Spencer
                          Jul 9 '13 at 20:03






                        • 21




                          Very practical but ugly as hell. I don't recommend it as it leads to confusing code.
                          – Daniel San
                          Mar 25 '14 at 22:54






                        • 26




                          Ugly code can be minimized by making it a method in your own "StringUtils" class. Then the ugly code is in exactly one spot, and everywhere else is nicely readable.
                          – RonR
                          Jun 5 '14 at 16:54






                        • 22




                          The loop method is much faster than this. Especially when wanting to count a char instead of a String (since there is no String.replace(char, char) method). On a 15 character string, I get a difference of 6049 ns vs 26,739 ns (averaged over 100runs). Raw numbers are huge difference, but percetage wise...it adds up. Avoid the memory allocations - use a loop!
                          – Ben
                          Nov 18 '14 at 15:41













                        up vote
                        909
                        down vote










                        up vote
                        909
                        down vote









                        How about this. It doesn't use regexp underneath so should be faster than some of the other solutions and won't use a loop.



                        int count = line.length() - line.replace(".", "").length();





                        share|improve this answer












                        How about this. It doesn't use regexp underneath so should be faster than some of the other solutions and won't use a loop.



                        int count = line.length() - line.replace(".", "").length();






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 18 '12 at 13:17









                        Andreas Wederbrand

                        26.5k64765




                        26.5k64765








                        • 107




                          Easiest way. Clever one. And it works on Android, where there is no StringUtils class
                          – Jose_GD
                          Nov 6 '12 at 13:12








                        • 35




                          This is the best answer. The reason it is the best is because you don't have to import another library.
                          – Alex Spencer
                          Jul 9 '13 at 20:03






                        • 21




                          Very practical but ugly as hell. I don't recommend it as it leads to confusing code.
                          – Daniel San
                          Mar 25 '14 at 22:54






                        • 26




                          Ugly code can be minimized by making it a method in your own "StringUtils" class. Then the ugly code is in exactly one spot, and everywhere else is nicely readable.
                          – RonR
                          Jun 5 '14 at 16:54






                        • 22




                          The loop method is much faster than this. Especially when wanting to count a char instead of a String (since there is no String.replace(char, char) method). On a 15 character string, I get a difference of 6049 ns vs 26,739 ns (averaged over 100runs). Raw numbers are huge difference, but percetage wise...it adds up. Avoid the memory allocations - use a loop!
                          – Ben
                          Nov 18 '14 at 15:41














                        • 107




                          Easiest way. Clever one. And it works on Android, where there is no StringUtils class
                          – Jose_GD
                          Nov 6 '12 at 13:12








                        • 35




                          This is the best answer. The reason it is the best is because you don't have to import another library.
                          – Alex Spencer
                          Jul 9 '13 at 20:03






                        • 21




                          Very practical but ugly as hell. I don't recommend it as it leads to confusing code.
                          – Daniel San
                          Mar 25 '14 at 22:54






                        • 26




                          Ugly code can be minimized by making it a method in your own "StringUtils" class. Then the ugly code is in exactly one spot, and everywhere else is nicely readable.
                          – RonR
                          Jun 5 '14 at 16:54






                        • 22




                          The loop method is much faster than this. Especially when wanting to count a char instead of a String (since there is no String.replace(char, char) method). On a 15 character string, I get a difference of 6049 ns vs 26,739 ns (averaged over 100runs). Raw numbers are huge difference, but percetage wise...it adds up. Avoid the memory allocations - use a loop!
                          – Ben
                          Nov 18 '14 at 15:41








                        107




                        107




                        Easiest way. Clever one. And it works on Android, where there is no StringUtils class
                        – Jose_GD
                        Nov 6 '12 at 13:12






                        Easiest way. Clever one. And it works on Android, where there is no StringUtils class
                        – Jose_GD
                        Nov 6 '12 at 13:12






                        35




                        35




                        This is the best answer. The reason it is the best is because you don't have to import another library.
                        – Alex Spencer
                        Jul 9 '13 at 20:03




                        This is the best answer. The reason it is the best is because you don't have to import another library.
                        – Alex Spencer
                        Jul 9 '13 at 20:03




                        21




                        21




                        Very practical but ugly as hell. I don't recommend it as it leads to confusing code.
                        – Daniel San
                        Mar 25 '14 at 22:54




                        Very practical but ugly as hell. I don't recommend it as it leads to confusing code.
                        – Daniel San
                        Mar 25 '14 at 22:54




                        26




                        26




                        Ugly code can be minimized by making it a method in your own "StringUtils" class. Then the ugly code is in exactly one spot, and everywhere else is nicely readable.
                        – RonR
                        Jun 5 '14 at 16:54




                        Ugly code can be minimized by making it a method in your own "StringUtils" class. Then the ugly code is in exactly one spot, and everywhere else is nicely readable.
                        – RonR
                        Jun 5 '14 at 16:54




                        22




                        22




                        The loop method is much faster than this. Especially when wanting to count a char instead of a String (since there is no String.replace(char, char) method). On a 15 character string, I get a difference of 6049 ns vs 26,739 ns (averaged over 100runs). Raw numbers are huge difference, but percetage wise...it adds up. Avoid the memory allocations - use a loop!
                        – Ben
                        Nov 18 '14 at 15:41




                        The loop method is much faster than this. Especially when wanting to count a char instead of a String (since there is no String.replace(char, char) method). On a 15 character string, I get a difference of 6049 ns vs 26,739 ns (averaged over 100runs). Raw numbers are huge difference, but percetage wise...it adds up. Avoid the memory allocations - use a loop!
                        – Ben
                        Nov 18 '14 at 15:41










                        up vote
                        212
                        down vote













                        Summarize other answer and what I know all ways to do this using a one-liner:



                           String testString = "a.b.c.d";


                        1) Using Apache Commons



                        int apache = StringUtils.countMatches(testString, ".");
                        System.out.println("apache = " + apache);


                        2) Using Spring Framework's



                        int spring = org.springframework.util.StringUtils.countOccurrencesOf(testString, ".");
                        System.out.println("spring = " + spring);


                        3) Using replace



                        int replace = testString.length() - testString.replace(".", "").length();
                        System.out.println("replace = " + replace);


                        4) Using replaceAll (case 1)



                        int replaceAll = testString.replaceAll("[^.]", "").length();
                        System.out.println("replaceAll = " + replaceAll);


                        5) Using replaceAll (case 2)



                        int replaceAllCase2 = testString.length() - testString.replaceAll("\.", "").length();
                        System.out.println("replaceAll (second case) = " + replaceAllCase2);


                        6) Using split



                        int split = testString.split("\.",-1).length-1;
                        System.out.println("split = " + split);


                        7) Using Java8 (case 1)



                        long java8 = testString.chars().filter(ch -> ch =='.').count();
                        System.out.println("java8 = " + java8);


                        8) Using Java8 (case 2), may be better for unicode than case 1



                        long java8Case2 = testString.codePoints().filter(ch -> ch =='.').count();
                        System.out.println("java8 (second case) = " + java8Case2);


                        9) Using StringTokenizer



                        int stringTokenizer = new StringTokenizer(" " +testString + " ", ".").countTokens()-1;
                        System.out.println("stringTokenizer = " + stringTokenizer);


                        From comment: Be carefull for the StringTokenizer, for a.b.c.d it will work but for a...b.c....d or ...a.b.c.d or a....b......c.....d... or etc. it will not work. It just will count for . between characters just once



                        More info in github



                        Perfomance test (using JMH, mode = AverageTime, score 0.010 better then 0.351):



                        Benchmark              Mode  Cnt  Score    Error  Units
                        1. countMatches avgt 5 0.010 ± 0.001 us/op
                        2. countOccurrencesOf avgt 5 0.010 ± 0.001 us/op
                        3. stringTokenizer avgt 5 0.028 ± 0.002 us/op
                        4. java8_1 avgt 5 0.077 ± 0.005 us/op
                        5. java8_2 avgt 5 0.078 ± 0.003 us/op
                        6. split avgt 5 0.137 ± 0.009 us/op
                        7. replaceAll_2 avgt 5 0.302 ± 0.047 us/op
                        8. replace avgt 5 0.303 ± 0.034 us/op
                        9. replaceAll_1 avgt 5 0.351 ± 0.045 us/op





                        share|improve this answer























                        • Pt.6 works perfectly
                          – vikramvi
                          Dec 13 '16 at 14:35






                        • 3




                          Could you add Guava?
                          – koppor
                          Apr 16 '17 at 19:44










                        • The printed strings do not match the ones above, and the order is fastest first which makes lookup tricky at least. Nice answer otherways!
                          – Maarten Bodewes
                          Jun 1 '17 at 11:05










                        • case 2, generalized for codepoints that need more than one UTF-16 code unit: "1🚲2🚲3 has 2".codePoints().filter((c) -> c == "🚲".codePointAt(0)).count()
                          – Tom Blodget
                          Aug 1 at 22:50















                        up vote
                        212
                        down vote













                        Summarize other answer and what I know all ways to do this using a one-liner:



                           String testString = "a.b.c.d";


                        1) Using Apache Commons



                        int apache = StringUtils.countMatches(testString, ".");
                        System.out.println("apache = " + apache);


                        2) Using Spring Framework's



                        int spring = org.springframework.util.StringUtils.countOccurrencesOf(testString, ".");
                        System.out.println("spring = " + spring);


                        3) Using replace



                        int replace = testString.length() - testString.replace(".", "").length();
                        System.out.println("replace = " + replace);


                        4) Using replaceAll (case 1)



                        int replaceAll = testString.replaceAll("[^.]", "").length();
                        System.out.println("replaceAll = " + replaceAll);


                        5) Using replaceAll (case 2)



                        int replaceAllCase2 = testString.length() - testString.replaceAll("\.", "").length();
                        System.out.println("replaceAll (second case) = " + replaceAllCase2);


                        6) Using split



                        int split = testString.split("\.",-1).length-1;
                        System.out.println("split = " + split);


                        7) Using Java8 (case 1)



                        long java8 = testString.chars().filter(ch -> ch =='.').count();
                        System.out.println("java8 = " + java8);


                        8) Using Java8 (case 2), may be better for unicode than case 1



                        long java8Case2 = testString.codePoints().filter(ch -> ch =='.').count();
                        System.out.println("java8 (second case) = " + java8Case2);


                        9) Using StringTokenizer



                        int stringTokenizer = new StringTokenizer(" " +testString + " ", ".").countTokens()-1;
                        System.out.println("stringTokenizer = " + stringTokenizer);


                        From comment: Be carefull for the StringTokenizer, for a.b.c.d it will work but for a...b.c....d or ...a.b.c.d or a....b......c.....d... or etc. it will not work. It just will count for . between characters just once



                        More info in github



                        Perfomance test (using JMH, mode = AverageTime, score 0.010 better then 0.351):



                        Benchmark              Mode  Cnt  Score    Error  Units
                        1. countMatches avgt 5 0.010 ± 0.001 us/op
                        2. countOccurrencesOf avgt 5 0.010 ± 0.001 us/op
                        3. stringTokenizer avgt 5 0.028 ± 0.002 us/op
                        4. java8_1 avgt 5 0.077 ± 0.005 us/op
                        5. java8_2 avgt 5 0.078 ± 0.003 us/op
                        6. split avgt 5 0.137 ± 0.009 us/op
                        7. replaceAll_2 avgt 5 0.302 ± 0.047 us/op
                        8. replace avgt 5 0.303 ± 0.034 us/op
                        9. replaceAll_1 avgt 5 0.351 ± 0.045 us/op





                        share|improve this answer























                        • Pt.6 works perfectly
                          – vikramvi
                          Dec 13 '16 at 14:35






                        • 3




                          Could you add Guava?
                          – koppor
                          Apr 16 '17 at 19:44










                        • The printed strings do not match the ones above, and the order is fastest first which makes lookup tricky at least. Nice answer otherways!
                          – Maarten Bodewes
                          Jun 1 '17 at 11:05










                        • case 2, generalized for codepoints that need more than one UTF-16 code unit: "1🚲2🚲3 has 2".codePoints().filter((c) -> c == "🚲".codePointAt(0)).count()
                          – Tom Blodget
                          Aug 1 at 22:50













                        up vote
                        212
                        down vote










                        up vote
                        212
                        down vote









                        Summarize other answer and what I know all ways to do this using a one-liner:



                           String testString = "a.b.c.d";


                        1) Using Apache Commons



                        int apache = StringUtils.countMatches(testString, ".");
                        System.out.println("apache = " + apache);


                        2) Using Spring Framework's



                        int spring = org.springframework.util.StringUtils.countOccurrencesOf(testString, ".");
                        System.out.println("spring = " + spring);


                        3) Using replace



                        int replace = testString.length() - testString.replace(".", "").length();
                        System.out.println("replace = " + replace);


                        4) Using replaceAll (case 1)



                        int replaceAll = testString.replaceAll("[^.]", "").length();
                        System.out.println("replaceAll = " + replaceAll);


                        5) Using replaceAll (case 2)



                        int replaceAllCase2 = testString.length() - testString.replaceAll("\.", "").length();
                        System.out.println("replaceAll (second case) = " + replaceAllCase2);


                        6) Using split



                        int split = testString.split("\.",-1).length-1;
                        System.out.println("split = " + split);


                        7) Using Java8 (case 1)



                        long java8 = testString.chars().filter(ch -> ch =='.').count();
                        System.out.println("java8 = " + java8);


                        8) Using Java8 (case 2), may be better for unicode than case 1



                        long java8Case2 = testString.codePoints().filter(ch -> ch =='.').count();
                        System.out.println("java8 (second case) = " + java8Case2);


                        9) Using StringTokenizer



                        int stringTokenizer = new StringTokenizer(" " +testString + " ", ".").countTokens()-1;
                        System.out.println("stringTokenizer = " + stringTokenizer);


                        From comment: Be carefull for the StringTokenizer, for a.b.c.d it will work but for a...b.c....d or ...a.b.c.d or a....b......c.....d... or etc. it will not work. It just will count for . between characters just once



                        More info in github



                        Perfomance test (using JMH, mode = AverageTime, score 0.010 better then 0.351):



                        Benchmark              Mode  Cnt  Score    Error  Units
                        1. countMatches avgt 5 0.010 ± 0.001 us/op
                        2. countOccurrencesOf avgt 5 0.010 ± 0.001 us/op
                        3. stringTokenizer avgt 5 0.028 ± 0.002 us/op
                        4. java8_1 avgt 5 0.077 ± 0.005 us/op
                        5. java8_2 avgt 5 0.078 ± 0.003 us/op
                        6. split avgt 5 0.137 ± 0.009 us/op
                        7. replaceAll_2 avgt 5 0.302 ± 0.047 us/op
                        8. replace avgt 5 0.303 ± 0.034 us/op
                        9. replaceAll_1 avgt 5 0.351 ± 0.045 us/op





                        share|improve this answer














                        Summarize other answer and what I know all ways to do this using a one-liner:



                           String testString = "a.b.c.d";


                        1) Using Apache Commons



                        int apache = StringUtils.countMatches(testString, ".");
                        System.out.println("apache = " + apache);


                        2) Using Spring Framework's



                        int spring = org.springframework.util.StringUtils.countOccurrencesOf(testString, ".");
                        System.out.println("spring = " + spring);


                        3) Using replace



                        int replace = testString.length() - testString.replace(".", "").length();
                        System.out.println("replace = " + replace);


                        4) Using replaceAll (case 1)



                        int replaceAll = testString.replaceAll("[^.]", "").length();
                        System.out.println("replaceAll = " + replaceAll);


                        5) Using replaceAll (case 2)



                        int replaceAllCase2 = testString.length() - testString.replaceAll("\.", "").length();
                        System.out.println("replaceAll (second case) = " + replaceAllCase2);


                        6) Using split



                        int split = testString.split("\.",-1).length-1;
                        System.out.println("split = " + split);


                        7) Using Java8 (case 1)



                        long java8 = testString.chars().filter(ch -> ch =='.').count();
                        System.out.println("java8 = " + java8);


                        8) Using Java8 (case 2), may be better for unicode than case 1



                        long java8Case2 = testString.codePoints().filter(ch -> ch =='.').count();
                        System.out.println("java8 (second case) = " + java8Case2);


                        9) Using StringTokenizer



                        int stringTokenizer = new StringTokenizer(" " +testString + " ", ".").countTokens()-1;
                        System.out.println("stringTokenizer = " + stringTokenizer);


                        From comment: Be carefull for the StringTokenizer, for a.b.c.d it will work but for a...b.c....d or ...a.b.c.d or a....b......c.....d... or etc. it will not work. It just will count for . between characters just once



                        More info in github



                        Perfomance test (using JMH, mode = AverageTime, score 0.010 better then 0.351):



                        Benchmark              Mode  Cnt  Score    Error  Units
                        1. countMatches avgt 5 0.010 ± 0.001 us/op
                        2. countOccurrencesOf avgt 5 0.010 ± 0.001 us/op
                        3. stringTokenizer avgt 5 0.028 ± 0.002 us/op
                        4. java8_1 avgt 5 0.077 ± 0.005 us/op
                        5. java8_2 avgt 5 0.078 ± 0.003 us/op
                        6. split avgt 5 0.137 ± 0.009 us/op
                        7. replaceAll_2 avgt 5 0.302 ± 0.047 us/op
                        8. replace avgt 5 0.303 ± 0.034 us/op
                        9. replaceAll_1 avgt 5 0.351 ± 0.045 us/op






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Apr 18 '16 at 17:54

























                        answered Feb 6 '16 at 15:40









                        Viacheslav Vedenin

                        32.6k123253




                        32.6k123253












                        • Pt.6 works perfectly
                          – vikramvi
                          Dec 13 '16 at 14:35






                        • 3




                          Could you add Guava?
                          – koppor
                          Apr 16 '17 at 19:44










                        • The printed strings do not match the ones above, and the order is fastest first which makes lookup tricky at least. Nice answer otherways!
                          – Maarten Bodewes
                          Jun 1 '17 at 11:05










                        • case 2, generalized for codepoints that need more than one UTF-16 code unit: "1🚲2🚲3 has 2".codePoints().filter((c) -> c == "🚲".codePointAt(0)).count()
                          – Tom Blodget
                          Aug 1 at 22:50


















                        • Pt.6 works perfectly
                          – vikramvi
                          Dec 13 '16 at 14:35






                        • 3




                          Could you add Guava?
                          – koppor
                          Apr 16 '17 at 19:44










                        • The printed strings do not match the ones above, and the order is fastest first which makes lookup tricky at least. Nice answer otherways!
                          – Maarten Bodewes
                          Jun 1 '17 at 11:05










                        • case 2, generalized for codepoints that need more than one UTF-16 code unit: "1🚲2🚲3 has 2".codePoints().filter((c) -> c == "🚲".codePointAt(0)).count()
                          – Tom Blodget
                          Aug 1 at 22:50
















                        Pt.6 works perfectly
                        – vikramvi
                        Dec 13 '16 at 14:35




                        Pt.6 works perfectly
                        – vikramvi
                        Dec 13 '16 at 14:35




                        3




                        3




                        Could you add Guava?
                        – koppor
                        Apr 16 '17 at 19:44




                        Could you add Guava?
                        – koppor
                        Apr 16 '17 at 19:44












                        The printed strings do not match the ones above, and the order is fastest first which makes lookup tricky at least. Nice answer otherways!
                        – Maarten Bodewes
                        Jun 1 '17 at 11:05




                        The printed strings do not match the ones above, and the order is fastest first which makes lookup tricky at least. Nice answer otherways!
                        – Maarten Bodewes
                        Jun 1 '17 at 11:05












                        case 2, generalized for codepoints that need more than one UTF-16 code unit: "1🚲2🚲3 has 2".codePoints().filter((c) -> c == "🚲".codePointAt(0)).count()
                        – Tom Blodget
                        Aug 1 at 22:50




                        case 2, generalized for codepoints that need more than one UTF-16 code unit: "1🚲2🚲3 has 2".codePoints().filter((c) -> c == "🚲".codePointAt(0)).count()
                        – Tom Blodget
                        Aug 1 at 22:50










                        up vote
                        167
                        down vote













                        Sooner or later, something has to loop. It's far simpler for you to write the (very simple) loop than to use something like split which is much more powerful than you need.



                        By all means encapsulate the loop in a separate method, e.g.



                        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;
                        }


                        Then you don't need have the loop in your main code - but the loop has to be there somewhere.






                        share|improve this answer

















                        • 4




                          for (int i=0,l=haystack.length(); i < l; i++) be kind to your stack
                          – Chris
                          Nov 29 '09 at 13:43






                        • 12




                          (I'm not even sure where the "stack" bit of the comment comes from. It's not like this answer is my recursive one, which is indeed nasty to the stack.)
                          – Jon Skeet
                          Nov 29 '09 at 14:51






                        • 2




                          not only that but this is possibly an anti optimization without taking a look at what the jit does. If you did the above on an array for loop for example you might make things worse.
                          – ShuggyCoUk
                          Nov 30 '09 at 11:15






                        • 3




                          @sulai: Chris's concern is baseless, IMO, in the face of a trivial JIT optimization. Is there any reason that comment drew your attention at the moment, over three years later? Just interested.
                          – Jon Skeet
                          Jun 12 '14 at 13:39






                        • 1




                          Probably @sulai just came across the question as I did (while wondering if Java had a built-in method for this) and didn't notice the dates. However, I'm curious how moving the length() call outside of the loop could make performance worse, as mentioned by @ShuggyCoUk a few comments up.
                          – JKillian
                          Jul 30 '14 at 2:19















                        up vote
                        167
                        down vote













                        Sooner or later, something has to loop. It's far simpler for you to write the (very simple) loop than to use something like split which is much more powerful than you need.



                        By all means encapsulate the loop in a separate method, e.g.



                        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;
                        }


                        Then you don't need have the loop in your main code - but the loop has to be there somewhere.






                        share|improve this answer

















                        • 4




                          for (int i=0,l=haystack.length(); i < l; i++) be kind to your stack
                          – Chris
                          Nov 29 '09 at 13:43






                        • 12




                          (I'm not even sure where the "stack" bit of the comment comes from. It's not like this answer is my recursive one, which is indeed nasty to the stack.)
                          – Jon Skeet
                          Nov 29 '09 at 14:51






                        • 2




                          not only that but this is possibly an anti optimization without taking a look at what the jit does. If you did the above on an array for loop for example you might make things worse.
                          – ShuggyCoUk
                          Nov 30 '09 at 11:15






                        • 3




                          @sulai: Chris's concern is baseless, IMO, in the face of a trivial JIT optimization. Is there any reason that comment drew your attention at the moment, over three years later? Just interested.
                          – Jon Skeet
                          Jun 12 '14 at 13:39






                        • 1




                          Probably @sulai just came across the question as I did (while wondering if Java had a built-in method for this) and didn't notice the dates. However, I'm curious how moving the length() call outside of the loop could make performance worse, as mentioned by @ShuggyCoUk a few comments up.
                          – JKillian
                          Jul 30 '14 at 2:19













                        up vote
                        167
                        down vote










                        up vote
                        167
                        down vote









                        Sooner or later, something has to loop. It's far simpler for you to write the (very simple) loop than to use something like split which is much more powerful than you need.



                        By all means encapsulate the loop in a separate method, e.g.



                        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;
                        }


                        Then you don't need have the loop in your main code - but the loop has to be there somewhere.






                        share|improve this answer












                        Sooner or later, something has to loop. It's far simpler for you to write the (very simple) loop than to use something like split which is much more powerful than you need.



                        By all means encapsulate the loop in a separate method, e.g.



                        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;
                        }


                        Then you don't need have the loop in your main code - but the loop has to be there somewhere.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 9 '08 at 14:38









                        Jon Skeet

                        1073k67378598393




                        1073k67378598393








                        • 4




                          for (int i=0,l=haystack.length(); i < l; i++) be kind to your stack
                          – Chris
                          Nov 29 '09 at 13:43






                        • 12




                          (I'm not even sure where the "stack" bit of the comment comes from. It's not like this answer is my recursive one, which is indeed nasty to the stack.)
                          – Jon Skeet
                          Nov 29 '09 at 14:51






                        • 2




                          not only that but this is possibly an anti optimization without taking a look at what the jit does. If you did the above on an array for loop for example you might make things worse.
                          – ShuggyCoUk
                          Nov 30 '09 at 11:15






                        • 3




                          @sulai: Chris's concern is baseless, IMO, in the face of a trivial JIT optimization. Is there any reason that comment drew your attention at the moment, over three years later? Just interested.
                          – Jon Skeet
                          Jun 12 '14 at 13:39






                        • 1




                          Probably @sulai just came across the question as I did (while wondering if Java had a built-in method for this) and didn't notice the dates. However, I'm curious how moving the length() call outside of the loop could make performance worse, as mentioned by @ShuggyCoUk a few comments up.
                          – JKillian
                          Jul 30 '14 at 2:19














                        • 4




                          for (int i=0,l=haystack.length(); i < l; i++) be kind to your stack
                          – Chris
                          Nov 29 '09 at 13:43






                        • 12




                          (I'm not even sure where the "stack" bit of the comment comes from. It's not like this answer is my recursive one, which is indeed nasty to the stack.)
                          – Jon Skeet
                          Nov 29 '09 at 14:51






                        • 2




                          not only that but this is possibly an anti optimization without taking a look at what the jit does. If you did the above on an array for loop for example you might make things worse.
                          – ShuggyCoUk
                          Nov 30 '09 at 11:15






                        • 3




                          @sulai: Chris's concern is baseless, IMO, in the face of a trivial JIT optimization. Is there any reason that comment drew your attention at the moment, over three years later? Just interested.
                          – Jon Skeet
                          Jun 12 '14 at 13:39






                        • 1




                          Probably @sulai just came across the question as I did (while wondering if Java had a built-in method for this) and didn't notice the dates. However, I'm curious how moving the length() call outside of the loop could make performance worse, as mentioned by @ShuggyCoUk a few comments up.
                          – JKillian
                          Jul 30 '14 at 2:19








                        4




                        4




                        for (int i=0,l=haystack.length(); i < l; i++) be kind to your stack
                        – Chris
                        Nov 29 '09 at 13:43




                        for (int i=0,l=haystack.length(); i < l; i++) be kind to your stack
                        – Chris
                        Nov 29 '09 at 13:43




                        12




                        12




                        (I'm not even sure where the "stack" bit of the comment comes from. It's not like this answer is my recursive one, which is indeed nasty to the stack.)
                        – Jon Skeet
                        Nov 29 '09 at 14:51




                        (I'm not even sure where the "stack" bit of the comment comes from. It's not like this answer is my recursive one, which is indeed nasty to the stack.)
                        – Jon Skeet
                        Nov 29 '09 at 14:51




                        2




                        2




                        not only that but this is possibly an anti optimization without taking a look at what the jit does. If you did the above on an array for loop for example you might make things worse.
                        – ShuggyCoUk
                        Nov 30 '09 at 11:15




                        not only that but this is possibly an anti optimization without taking a look at what the jit does. If you did the above on an array for loop for example you might make things worse.
                        – ShuggyCoUk
                        Nov 30 '09 at 11:15




                        3




                        3




                        @sulai: Chris's concern is baseless, IMO, in the face of a trivial JIT optimization. Is there any reason that comment drew your attention at the moment, over three years later? Just interested.
                        – Jon Skeet
                        Jun 12 '14 at 13:39




                        @sulai: Chris's concern is baseless, IMO, in the face of a trivial JIT optimization. Is there any reason that comment drew your attention at the moment, over three years later? Just interested.
                        – Jon Skeet
                        Jun 12 '14 at 13:39




                        1




                        1




                        Probably @sulai just came across the question as I did (while wondering if Java had a built-in method for this) and didn't notice the dates. However, I'm curious how moving the length() call outside of the loop could make performance worse, as mentioned by @ShuggyCoUk a few comments up.
                        – JKillian
                        Jul 30 '14 at 2:19




                        Probably @sulai just came across the question as I did (while wondering if Java had a built-in method for this) and didn't notice the dates. However, I'm curious how moving the length() call outside of the loop could make performance worse, as mentioned by @ShuggyCoUk a few comments up.
                        – JKillian
                        Jul 30 '14 at 2:19










                        up vote
                        60
                        down vote













                        I had an idea similar to Mladen, but the opposite...



                        String s = "a.b.c.d";
                        int charCount = s.replaceAll("[^.]", "").length();
                        println(charCount);





                        share|improve this answer























                        • Correct. ReplaceAll(".") would replace any character, not just dot. ReplaceAll("\.") would have worked. Your solution is more straightforward.
                          – VonC
                          Nov 9 '08 at 16:20










                        • jjnguy had actually suggested a replaceAll("[^.]") first, upon seeing my "a.b.c.d".split("\.").length-1 solution. But after being hit 5 times, I deleted my answer (and his comment).
                          – VonC
                          Nov 9 '08 at 16:24










                        • "...now you have two problems" (oblig.) Anyway, I'd bet that there are tens of loops executing in replaceAll() and length(). Well, if it's not visible, it doesn't exist ;o)
                          – Piskvor
                          Aug 25 '10 at 11:22






                        • 2




                          i don't think it's a good idea to use regex and create a new string for the counting. i would just create a static method that loop every character in the string to count the number.
                          – mingfai
                          Apr 23 '11 at 23:14






                        • 1




                          @mingfai: indeed, but the original question is about making a one-liner, and even, without a loop (you can do a loop in one line, but it will be ugly!). Question the question, not the answer... :-)
                          – PhiLho
                          Apr 26 '11 at 17:25















                        up vote
                        60
                        down vote













                        I had an idea similar to Mladen, but the opposite...



                        String s = "a.b.c.d";
                        int charCount = s.replaceAll("[^.]", "").length();
                        println(charCount);





                        share|improve this answer























                        • Correct. ReplaceAll(".") would replace any character, not just dot. ReplaceAll("\.") would have worked. Your solution is more straightforward.
                          – VonC
                          Nov 9 '08 at 16:20










                        • jjnguy had actually suggested a replaceAll("[^.]") first, upon seeing my "a.b.c.d".split("\.").length-1 solution. But after being hit 5 times, I deleted my answer (and his comment).
                          – VonC
                          Nov 9 '08 at 16:24










                        • "...now you have two problems" (oblig.) Anyway, I'd bet that there are tens of loops executing in replaceAll() and length(). Well, if it's not visible, it doesn't exist ;o)
                          – Piskvor
                          Aug 25 '10 at 11:22






                        • 2




                          i don't think it's a good idea to use regex and create a new string for the counting. i would just create a static method that loop every character in the string to count the number.
                          – mingfai
                          Apr 23 '11 at 23:14






                        • 1




                          @mingfai: indeed, but the original question is about making a one-liner, and even, without a loop (you can do a loop in one line, but it will be ugly!). Question the question, not the answer... :-)
                          – PhiLho
                          Apr 26 '11 at 17:25













                        up vote
                        60
                        down vote










                        up vote
                        60
                        down vote









                        I had an idea similar to Mladen, but the opposite...



                        String s = "a.b.c.d";
                        int charCount = s.replaceAll("[^.]", "").length();
                        println(charCount);





                        share|improve this answer














                        I had an idea similar to Mladen, but the opposite...



                        String s = "a.b.c.d";
                        int charCount = s.replaceAll("[^.]", "").length();
                        println(charCount);






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Nov 12 '08 at 21:32

























                        answered Nov 9 '08 at 16:16









                        PhiLho

                        34.7k378121




                        34.7k378121












                        • Correct. ReplaceAll(".") would replace any character, not just dot. ReplaceAll("\.") would have worked. Your solution is more straightforward.
                          – VonC
                          Nov 9 '08 at 16:20










                        • jjnguy had actually suggested a replaceAll("[^.]") first, upon seeing my "a.b.c.d".split("\.").length-1 solution. But after being hit 5 times, I deleted my answer (and his comment).
                          – VonC
                          Nov 9 '08 at 16:24










                        • "...now you have two problems" (oblig.) Anyway, I'd bet that there are tens of loops executing in replaceAll() and length(). Well, if it's not visible, it doesn't exist ;o)
                          – Piskvor
                          Aug 25 '10 at 11:22






                        • 2




                          i don't think it's a good idea to use regex and create a new string for the counting. i would just create a static method that loop every character in the string to count the number.
                          – mingfai
                          Apr 23 '11 at 23:14






                        • 1




                          @mingfai: indeed, but the original question is about making a one-liner, and even, without a loop (you can do a loop in one line, but it will be ugly!). Question the question, not the answer... :-)
                          – PhiLho
                          Apr 26 '11 at 17:25


















                        • Correct. ReplaceAll(".") would replace any character, not just dot. ReplaceAll("\.") would have worked. Your solution is more straightforward.
                          – VonC
                          Nov 9 '08 at 16:20










                        • jjnguy had actually suggested a replaceAll("[^.]") first, upon seeing my "a.b.c.d".split("\.").length-1 solution. But after being hit 5 times, I deleted my answer (and his comment).
                          – VonC
                          Nov 9 '08 at 16:24










                        • "...now you have two problems" (oblig.) Anyway, I'd bet that there are tens of loops executing in replaceAll() and length(). Well, if it's not visible, it doesn't exist ;o)
                          – Piskvor
                          Aug 25 '10 at 11:22






                        • 2




                          i don't think it's a good idea to use regex and create a new string for the counting. i would just create a static method that loop every character in the string to count the number.
                          – mingfai
                          Apr 23 '11 at 23:14






                        • 1




                          @mingfai: indeed, but the original question is about making a one-liner, and even, without a loop (you can do a loop in one line, but it will be ugly!). Question the question, not the answer... :-)
                          – PhiLho
                          Apr 26 '11 at 17:25
















                        Correct. ReplaceAll(".") would replace any character, not just dot. ReplaceAll("\.") would have worked. Your solution is more straightforward.
                        – VonC
                        Nov 9 '08 at 16:20




                        Correct. ReplaceAll(".") would replace any character, not just dot. ReplaceAll("\.") would have worked. Your solution is more straightforward.
                        – VonC
                        Nov 9 '08 at 16:20












                        jjnguy had actually suggested a replaceAll("[^.]") first, upon seeing my "a.b.c.d".split("\.").length-1 solution. But after being hit 5 times, I deleted my answer (and his comment).
                        – VonC
                        Nov 9 '08 at 16:24




                        jjnguy had actually suggested a replaceAll("[^.]") first, upon seeing my "a.b.c.d".split("\.").length-1 solution. But after being hit 5 times, I deleted my answer (and his comment).
                        – VonC
                        Nov 9 '08 at 16:24












                        "...now you have two problems" (oblig.) Anyway, I'd bet that there are tens of loops executing in replaceAll() and length(). Well, if it's not visible, it doesn't exist ;o)
                        – Piskvor
                        Aug 25 '10 at 11:22




                        "...now you have two problems" (oblig.) Anyway, I'd bet that there are tens of loops executing in replaceAll() and length(). Well, if it's not visible, it doesn't exist ;o)
                        – Piskvor
                        Aug 25 '10 at 11:22




                        2




                        2




                        i don't think it's a good idea to use regex and create a new string for the counting. i would just create a static method that loop every character in the string to count the number.
                        – mingfai
                        Apr 23 '11 at 23:14




                        i don't think it's a good idea to use regex and create a new string for the counting. i would just create a static method that loop every character in the string to count the number.
                        – mingfai
                        Apr 23 '11 at 23:14




                        1




                        1




                        @mingfai: indeed, but the original question is about making a one-liner, and even, without a loop (you can do a loop in one line, but it will be ugly!). Question the question, not the answer... :-)
                        – PhiLho
                        Apr 26 '11 at 17:25




                        @mingfai: indeed, but the original question is about making a one-liner, and even, without a loop (you can do a loop in one line, but it will be ugly!). Question the question, not the answer... :-)
                        – PhiLho
                        Apr 26 '11 at 17:25










                        up vote
                        35
                        down vote













                        String s = "a.b.c.d";
                        int charCount = s.length() - s.replaceAll("\.", "").length();


                        ReplaceAll(".") would replace all characters.



                        PhiLho's solution uses ReplaceAll("[^.]",""), which does not need to be escaped, since [.] represents the character 'dot', not 'any character'.






                        share|improve this answer























                        • I like this one. There's still a loop there, of course, as there has to be.
                          – The Archetypal Paul
                          Nov 9 '08 at 15:13










                        • Untested, eh? :-)
                          – PhiLho
                          Nov 9 '08 at 16:14










                        • PhiLho's solution is better
                          – VonC
                          Nov 9 '08 at 16:31










                        • NB that you'd need to divide this number if you wanted to look for substrings of length > 1
                          – rogerdpack
                          Apr 3 '12 at 23:11















                        up vote
                        35
                        down vote













                        String s = "a.b.c.d";
                        int charCount = s.length() - s.replaceAll("\.", "").length();


                        ReplaceAll(".") would replace all characters.



                        PhiLho's solution uses ReplaceAll("[^.]",""), which does not need to be escaped, since [.] represents the character 'dot', not 'any character'.






                        share|improve this answer























                        • I like this one. There's still a loop there, of course, as there has to be.
                          – The Archetypal Paul
                          Nov 9 '08 at 15:13










                        • Untested, eh? :-)
                          – PhiLho
                          Nov 9 '08 at 16:14










                        • PhiLho's solution is better
                          – VonC
                          Nov 9 '08 at 16:31










                        • NB that you'd need to divide this number if you wanted to look for substrings of length > 1
                          – rogerdpack
                          Apr 3 '12 at 23:11













                        up vote
                        35
                        down vote










                        up vote
                        35
                        down vote









                        String s = "a.b.c.d";
                        int charCount = s.length() - s.replaceAll("\.", "").length();


                        ReplaceAll(".") would replace all characters.



                        PhiLho's solution uses ReplaceAll("[^.]",""), which does not need to be escaped, since [.] represents the character 'dot', not 'any character'.






                        share|improve this answer














                        String s = "a.b.c.d";
                        int charCount = s.length() - s.replaceAll("\.", "").length();


                        ReplaceAll(".") would replace all characters.



                        PhiLho's solution uses ReplaceAll("[^.]",""), which does not need to be escaped, since [.] represents the character 'dot', not 'any character'.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited May 23 '17 at 12:10









                        Community

                        11




                        11










                        answered Nov 9 '08 at 14:48









                        Mladen Prajdic

                        13.9k23243




                        13.9k23243












                        • I like this one. There's still a loop there, of course, as there has to be.
                          – The Archetypal Paul
                          Nov 9 '08 at 15:13










                        • Untested, eh? :-)
                          – PhiLho
                          Nov 9 '08 at 16:14










                        • PhiLho's solution is better
                          – VonC
                          Nov 9 '08 at 16:31










                        • NB that you'd need to divide this number if you wanted to look for substrings of length > 1
                          – rogerdpack
                          Apr 3 '12 at 23:11


















                        • I like this one. There's still a loop there, of course, as there has to be.
                          – The Archetypal Paul
                          Nov 9 '08 at 15:13










                        • Untested, eh? :-)
                          – PhiLho
                          Nov 9 '08 at 16:14










                        • PhiLho's solution is better
                          – VonC
                          Nov 9 '08 at 16:31










                        • NB that you'd need to divide this number if you wanted to look for substrings of length > 1
                          – rogerdpack
                          Apr 3 '12 at 23:11
















                        I like this one. There's still a loop there, of course, as there has to be.
                        – The Archetypal Paul
                        Nov 9 '08 at 15:13




                        I like this one. There's still a loop there, of course, as there has to be.
                        – The Archetypal Paul
                        Nov 9 '08 at 15:13












                        Untested, eh? :-)
                        – PhiLho
                        Nov 9 '08 at 16:14




                        Untested, eh? :-)
                        – PhiLho
                        Nov 9 '08 at 16:14












                        PhiLho's solution is better
                        – VonC
                        Nov 9 '08 at 16:31




                        PhiLho's solution is better
                        – VonC
                        Nov 9 '08 at 16:31












                        NB that you'd need to divide this number if you wanted to look for substrings of length > 1
                        – rogerdpack
                        Apr 3 '12 at 23:11




                        NB that you'd need to divide this number if you wanted to look for substrings of length > 1
                        – rogerdpack
                        Apr 3 '12 at 23:11










                        up vote
                        26
                        down vote













                        My 'idiomatic one-liner' solution:



                        int count = "a.b.c.d".length() - "a.b.c.d".replace(".", "").length();


                        Have no idea why a solution that uses StringUtils is accepted.






                        share|improve this answer

















                        • 3




                          There is an older solution similar to this one in this post.
                          – JCalcines
                          Feb 5 '14 at 9:24








                        • 6




                          Because this solution is really inefficient
                          – András
                          May 14 '15 at 9:41










                        • This creates an extra string just to produce a count. No idea why anyone would prefer this over StringUtils if StringUtils is an option. If it's not an option, they should just create a simple for loop in a utility class.
                          – crush
                          May 28 '16 at 20:15















                        up vote
                        26
                        down vote













                        My 'idiomatic one-liner' solution:



                        int count = "a.b.c.d".length() - "a.b.c.d".replace(".", "").length();


                        Have no idea why a solution that uses StringUtils is accepted.






                        share|improve this answer

















                        • 3




                          There is an older solution similar to this one in this post.
                          – JCalcines
                          Feb 5 '14 at 9:24








                        • 6




                          Because this solution is really inefficient
                          – András
                          May 14 '15 at 9:41










                        • This creates an extra string just to produce a count. No idea why anyone would prefer this over StringUtils if StringUtils is an option. If it's not an option, they should just create a simple for loop in a utility class.
                          – crush
                          May 28 '16 at 20:15













                        up vote
                        26
                        down vote










                        up vote
                        26
                        down vote









                        My 'idiomatic one-liner' solution:



                        int count = "a.b.c.d".length() - "a.b.c.d".replace(".", "").length();


                        Have no idea why a solution that uses StringUtils is accepted.






                        share|improve this answer












                        My 'idiomatic one-liner' solution:



                        int count = "a.b.c.d".length() - "a.b.c.d".replace(".", "").length();


                        Have no idea why a solution that uses StringUtils is accepted.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 13 '13 at 19:30









                        mlchen850622

                        55847




                        55847








                        • 3




                          There is an older solution similar to this one in this post.
                          – JCalcines
                          Feb 5 '14 at 9:24








                        • 6




                          Because this solution is really inefficient
                          – András
                          May 14 '15 at 9:41










                        • This creates an extra string just to produce a count. No idea why anyone would prefer this over StringUtils if StringUtils is an option. If it's not an option, they should just create a simple for loop in a utility class.
                          – crush
                          May 28 '16 at 20:15














                        • 3




                          There is an older solution similar to this one in this post.
                          – JCalcines
                          Feb 5 '14 at 9:24








                        • 6




                          Because this solution is really inefficient
                          – András
                          May 14 '15 at 9:41










                        • This creates an extra string just to produce a count. No idea why anyone would prefer this over StringUtils if StringUtils is an option. If it's not an option, they should just create a simple for loop in a utility class.
                          – crush
                          May 28 '16 at 20:15








                        3




                        3




                        There is an older solution similar to this one in this post.
                        – JCalcines
                        Feb 5 '14 at 9:24






                        There is an older solution similar to this one in this post.
                        – JCalcines
                        Feb 5 '14 at 9:24






                        6




                        6




                        Because this solution is really inefficient
                        – András
                        May 14 '15 at 9:41




                        Because this solution is really inefficient
                        – András
                        May 14 '15 at 9:41












                        This creates an extra string just to produce a count. No idea why anyone would prefer this over StringUtils if StringUtils is an option. If it's not an option, they should just create a simple for loop in a utility class.
                        – crush
                        May 28 '16 at 20:15




                        This creates an extra string just to produce a count. No idea why anyone would prefer this over StringUtils if StringUtils is an option. If it's not an option, they should just create a simple for loop in a utility class.
                        – crush
                        May 28 '16 at 20:15










                        up vote
                        24
                        down vote













                        String s = "a.b.c.d";
                        long result = s.chars().filter(ch -> ch == '.').count();





                        share|improve this answer



















                        • 1




                          Vote + for a native solution.
                          – Scadge
                          Mar 23 '16 at 13:31















                        up vote
                        24
                        down vote













                        String s = "a.b.c.d";
                        long result = s.chars().filter(ch -> ch == '.').count();





                        share|improve this answer



















                        • 1




                          Vote + for a native solution.
                          – Scadge
                          Mar 23 '16 at 13:31













                        up vote
                        24
                        down vote










                        up vote
                        24
                        down vote









                        String s = "a.b.c.d";
                        long result = s.chars().filter(ch -> ch == '.').count();





                        share|improve this answer














                        String s = "a.b.c.d";
                        long result = s.chars().filter(ch -> ch == '.').count();






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jul 4 '15 at 1:24









                        Martin Andersson

                        8,39436293




                        8,39436293










                        answered Oct 11 '13 at 9:46









                        fubo

                        29.3k964103




                        29.3k964103








                        • 1




                          Vote + for a native solution.
                          – Scadge
                          Mar 23 '16 at 13:31














                        • 1




                          Vote + for a native solution.
                          – Scadge
                          Mar 23 '16 at 13:31








                        1




                        1




                        Vote + for a native solution.
                        – Scadge
                        Mar 23 '16 at 13:31




                        Vote + for a native solution.
                        – Scadge
                        Mar 23 '16 at 13:31










                        up vote
                        21
                        down vote













                        A shorter example is



                        String text = "a.b.c.d";
                        int count = text.split("\.",-1).length-1;





                        share|improve this answer

















                        • 2




                          This one seems to have a relatively large overhead, be warned that it may create a lot of small strings. Normally that does not matter much but use with care.
                          – Maarten Bodewes
                          Aug 30 '14 at 16:51















                        up vote
                        21
                        down vote













                        A shorter example is



                        String text = "a.b.c.d";
                        int count = text.split("\.",-1).length-1;





                        share|improve this answer

















                        • 2




                          This one seems to have a relatively large overhead, be warned that it may create a lot of small strings. Normally that does not matter much but use with care.
                          – Maarten Bodewes
                          Aug 30 '14 at 16:51













                        up vote
                        21
                        down vote










                        up vote
                        21
                        down vote









                        A shorter example is



                        String text = "a.b.c.d";
                        int count = text.split("\.",-1).length-1;





                        share|improve this answer












                        A shorter example is



                        String text = "a.b.c.d";
                        int count = text.split("\.",-1).length-1;






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 29 '09 at 13:40









                        Peter Lawrey

                        439k55557958




                        439k55557958








                        • 2




                          This one seems to have a relatively large overhead, be warned that it may create a lot of small strings. Normally that does not matter much but use with care.
                          – Maarten Bodewes
                          Aug 30 '14 at 16:51














                        • 2




                          This one seems to have a relatively large overhead, be warned that it may create a lot of small strings. Normally that does not matter much but use with care.
                          – Maarten Bodewes
                          Aug 30 '14 at 16:51








                        2




                        2




                        This one seems to have a relatively large overhead, be warned that it may create a lot of small strings. Normally that does not matter much but use with care.
                        – Maarten Bodewes
                        Aug 30 '14 at 16:51




                        This one seems to have a relatively large overhead, be warned that it may create a lot of small strings. Normally that does not matter much but use with care.
                        – Maarten Bodewes
                        Aug 30 '14 at 16:51










                        up vote
                        17
                        down vote













                        here is a solution without a loop:



                        public static int countOccurrences(String haystack, char needle, int i){
                        return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}


                        System.out.println("num of dots is "+countOccurrences("a.b.c.d",'.',0));


                        well, there is a loop, but it is invisible :-)



                        -- Yonatan






                        share|improve this answer

















                        • 2




                          Unless your string is so long you get an OutOfMemoryError.
                          – Spencer Kormos
                          Nov 9 '08 at 15:50










                        • The problem sounds contrived enough to be homework, and if so, this recursion is probably the answer you're being asked to find.
                          – erickson
                          Nov 9 '08 at 17:43










                        • That uses indexOf, which will loop... but a nice idea. Posting a truly "just recursive" solution in a minute...
                          – Jon Skeet
                          Nov 9 '08 at 18:03






                        • 1




                          LOL, so unnecessary.
                          – Bernard Igiri
                          Feb 16 '11 at 17:04










                        • If it has more occurrences that your available stack slots, you will have a stack overflow exception ;)
                          – Luca C.
                          Jun 2 '14 at 16:19

















                        up vote
                        17
                        down vote













                        here is a solution without a loop:



                        public static int countOccurrences(String haystack, char needle, int i){
                        return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}


                        System.out.println("num of dots is "+countOccurrences("a.b.c.d",'.',0));


                        well, there is a loop, but it is invisible :-)



                        -- Yonatan






                        share|improve this answer

















                        • 2




                          Unless your string is so long you get an OutOfMemoryError.
                          – Spencer Kormos
                          Nov 9 '08 at 15:50










                        • The problem sounds contrived enough to be homework, and if so, this recursion is probably the answer you're being asked to find.
                          – erickson
                          Nov 9 '08 at 17:43










                        • That uses indexOf, which will loop... but a nice idea. Posting a truly "just recursive" solution in a minute...
                          – Jon Skeet
                          Nov 9 '08 at 18:03






                        • 1




                          LOL, so unnecessary.
                          – Bernard Igiri
                          Feb 16 '11 at 17:04










                        • If it has more occurrences that your available stack slots, you will have a stack overflow exception ;)
                          – Luca C.
                          Jun 2 '14 at 16:19















                        up vote
                        17
                        down vote










                        up vote
                        17
                        down vote









                        here is a solution without a loop:



                        public static int countOccurrences(String haystack, char needle, int i){
                        return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}


                        System.out.println("num of dots is "+countOccurrences("a.b.c.d",'.',0));


                        well, there is a loop, but it is invisible :-)



                        -- Yonatan






                        share|improve this answer












                        here is a solution without a loop:



                        public static int countOccurrences(String haystack, char needle, int i){
                        return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}


                        System.out.println("num of dots is "+countOccurrences("a.b.c.d",'.',0));


                        well, there is a loop, but it is invisible :-)



                        -- Yonatan







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 9 '08 at 14:46









                        Yonatan Maman

                        1,6242031




                        1,6242031








                        • 2




                          Unless your string is so long you get an OutOfMemoryError.
                          – Spencer Kormos
                          Nov 9 '08 at 15:50










                        • The problem sounds contrived enough to be homework, and if so, this recursion is probably the answer you're being asked to find.
                          – erickson
                          Nov 9 '08 at 17:43










                        • That uses indexOf, which will loop... but a nice idea. Posting a truly "just recursive" solution in a minute...
                          – Jon Skeet
                          Nov 9 '08 at 18:03






                        • 1




                          LOL, so unnecessary.
                          – Bernard Igiri
                          Feb 16 '11 at 17:04










                        • If it has more occurrences that your available stack slots, you will have a stack overflow exception ;)
                          – Luca C.
                          Jun 2 '14 at 16:19
















                        • 2




                          Unless your string is so long you get an OutOfMemoryError.
                          – Spencer Kormos
                          Nov 9 '08 at 15:50










                        • The problem sounds contrived enough to be homework, and if so, this recursion is probably the answer you're being asked to find.
                          – erickson
                          Nov 9 '08 at 17:43










                        • That uses indexOf, which will loop... but a nice idea. Posting a truly "just recursive" solution in a minute...
                          – Jon Skeet
                          Nov 9 '08 at 18:03






                        • 1




                          LOL, so unnecessary.
                          – Bernard Igiri
                          Feb 16 '11 at 17:04










                        • If it has more occurrences that your available stack slots, you will have a stack overflow exception ;)
                          – Luca C.
                          Jun 2 '14 at 16:19










                        2




                        2




                        Unless your string is so long you get an OutOfMemoryError.
                        – Spencer Kormos
                        Nov 9 '08 at 15:50




                        Unless your string is so long you get an OutOfMemoryError.
                        – Spencer Kormos
                        Nov 9 '08 at 15:50












                        The problem sounds contrived enough to be homework, and if so, this recursion is probably the answer you're being asked to find.
                        – erickson
                        Nov 9 '08 at 17:43




                        The problem sounds contrived enough to be homework, and if so, this recursion is probably the answer you're being asked to find.
                        – erickson
                        Nov 9 '08 at 17:43












                        That uses indexOf, which will loop... but a nice idea. Posting a truly "just recursive" solution in a minute...
                        – Jon Skeet
                        Nov 9 '08 at 18:03




                        That uses indexOf, which will loop... but a nice idea. Posting a truly "just recursive" solution in a minute...
                        – Jon Skeet
                        Nov 9 '08 at 18:03




                        1




                        1




                        LOL, so unnecessary.
                        – Bernard Igiri
                        Feb 16 '11 at 17:04




                        LOL, so unnecessary.
                        – Bernard Igiri
                        Feb 16 '11 at 17:04












                        If it has more occurrences that your available stack slots, you will have a stack overflow exception ;)
                        – Luca C.
                        Jun 2 '14 at 16:19






                        If it has more occurrences that your available stack slots, you will have a stack overflow exception ;)
                        – Luca C.
                        Jun 2 '14 at 16:19












                        up vote
                        13
                        down vote













                        I don't like the idea of allocating a new string for this purpose. And as the string already has a char array in the back where it stores it's value, String.charAt() is practically free.



                        for(int i=0;i<s.length();num+=(s.charAt(i++)==delim?1:0))


                        does the trick, without additional allocations that need collection, in 1 line or less, with only J2SE.






                        share|improve this answer























                        • Giving some love for this one because it is the only one doing a single pass over the string. I DO care about performance .
                          – javadba
                          Jan 22 '14 at 20:19










                        • Why does this answer has so few votes? Seems to be the best to me.
                          – Pascal
                          May 26 '14 at 11:18








                        • 1




                          charAt iterates through 16 bit code points not characters! A char in Java is not a character. So this answer implies that there must be no Unicode symbol with a high surrogate being equal to the code point of delim. I am not sure if it is correct for the dot, but in general it might be not correct.
                          – ceving
                          Jul 22 '14 at 17:25

















                        up vote
                        13
                        down vote













                        I don't like the idea of allocating a new string for this purpose. And as the string already has a char array in the back where it stores it's value, String.charAt() is practically free.



                        for(int i=0;i<s.length();num+=(s.charAt(i++)==delim?1:0))


                        does the trick, without additional allocations that need collection, in 1 line or less, with only J2SE.






                        share|improve this answer























                        • Giving some love for this one because it is the only one doing a single pass over the string. I DO care about performance .
                          – javadba
                          Jan 22 '14 at 20:19










                        • Why does this answer has so few votes? Seems to be the best to me.
                          – Pascal
                          May 26 '14 at 11:18








                        • 1




                          charAt iterates through 16 bit code points not characters! A char in Java is not a character. So this answer implies that there must be no Unicode symbol with a high surrogate being equal to the code point of delim. I am not sure if it is correct for the dot, but in general it might be not correct.
                          – ceving
                          Jul 22 '14 at 17:25















                        up vote
                        13
                        down vote










                        up vote
                        13
                        down vote









                        I don't like the idea of allocating a new string for this purpose. And as the string already has a char array in the back where it stores it's value, String.charAt() is practically free.



                        for(int i=0;i<s.length();num+=(s.charAt(i++)==delim?1:0))


                        does the trick, without additional allocations that need collection, in 1 line or less, with only J2SE.






                        share|improve this answer














                        I don't like the idea of allocating a new string for this purpose. And as the string already has a char array in the back where it stores it's value, String.charAt() is practically free.



                        for(int i=0;i<s.length();num+=(s.charAt(i++)==delim?1:0))


                        does the trick, without additional allocations that need collection, in 1 line or less, with only J2SE.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Apr 30 '13 at 7:07

























                        answered Apr 16 '13 at 9:50









                        0xCAFEBABE

                        3,45232349




                        3,45232349












                        • Giving some love for this one because it is the only one doing a single pass over the string. I DO care about performance .
                          – javadba
                          Jan 22 '14 at 20:19










                        • Why does this answer has so few votes? Seems to be the best to me.
                          – Pascal
                          May 26 '14 at 11:18








                        • 1




                          charAt iterates through 16 bit code points not characters! A char in Java is not a character. So this answer implies that there must be no Unicode symbol with a high surrogate being equal to the code point of delim. I am not sure if it is correct for the dot, but in general it might be not correct.
                          – ceving
                          Jul 22 '14 at 17:25




















                        • Giving some love for this one because it is the only one doing a single pass over the string. I DO care about performance .
                          – javadba
                          Jan 22 '14 at 20:19










                        • Why does this answer has so few votes? Seems to be the best to me.
                          – Pascal
                          May 26 '14 at 11:18








                        • 1




                          charAt iterates through 16 bit code points not characters! A char in Java is not a character. So this answer implies that there must be no Unicode symbol with a high surrogate being equal to the code point of delim. I am not sure if it is correct for the dot, but in general it might be not correct.
                          – ceving
                          Jul 22 '14 at 17:25


















                        Giving some love for this one because it is the only one doing a single pass over the string. I DO care about performance .
                        – javadba
                        Jan 22 '14 at 20:19




                        Giving some love for this one because it is the only one doing a single pass over the string. I DO care about performance .
                        – javadba
                        Jan 22 '14 at 20:19












                        Why does this answer has so few votes? Seems to be the best to me.
                        – Pascal
                        May 26 '14 at 11:18






                        Why does this answer has so few votes? Seems to be the best to me.
                        – Pascal
                        May 26 '14 at 11:18






                        1




                        1




                        charAt iterates through 16 bit code points not characters! A char in Java is not a character. So this answer implies that there must be no Unicode symbol with a high surrogate being equal to the code point of delim. I am not sure if it is correct for the dot, but in general it might be not correct.
                        – ceving
                        Jul 22 '14 at 17:25






                        charAt iterates through 16 bit code points not characters! A char in Java is not a character. So this answer implies that there must be no Unicode symbol with a high surrogate being equal to the code point of delim. I am not sure if it is correct for the dot, but in general it might be not correct.
                        – ceving
                        Jul 22 '14 at 17:25












                        up vote
                        12
                        down vote













                        Okay, inspired by Yonatan's solution, here's one which is purely recursive - the only library methods used are length() and charAt(), neither of which do any looping:



                        public static int countOccurrences(String haystack, char needle)
                        {
                        return countOccurrences(haystack, needle, 0);
                        }

                        private static int countOccurrences(String haystack, char needle, int index)
                        {
                        if (index >= haystack.length())
                        {
                        return 0;
                        }

                        int contribution = haystack.charAt(index) == needle ? 1 : 0;
                        return contribution + countOccurrences(haystack, needle, index+1);
                        }


                        Whether recursion counts as looping depends on which exact definition you use, but it's probably as close as you'll get.



                        I don't know whether most JVMs do tail-recursion these days... if not you'll get the eponymous stack overflow for suitably long strings, of course.






                        share|improve this answer























                        • No, tail recursion will probably be in Java 7, but it's not widespread yet. This simple, direct tail recursion could be translated to a loop at compile time, but the Java 7 stuff is actually built-in to the JVM to handle chaining through different methods.
                          – erickson
                          Nov 10 '08 at 20:11






                        • 3




                          You'd be more likely to get tail recursion if your method returned a call to itself (including a running total parameter), rather than returning the result of performing an addition.
                          – Stephen Denne
                          Mar 20 '09 at 10:56















                        up vote
                        12
                        down vote













                        Okay, inspired by Yonatan's solution, here's one which is purely recursive - the only library methods used are length() and charAt(), neither of which do any looping:



                        public static int countOccurrences(String haystack, char needle)
                        {
                        return countOccurrences(haystack, needle, 0);
                        }

                        private static int countOccurrences(String haystack, char needle, int index)
                        {
                        if (index >= haystack.length())
                        {
                        return 0;
                        }

                        int contribution = haystack.charAt(index) == needle ? 1 : 0;
                        return contribution + countOccurrences(haystack, needle, index+1);
                        }


                        Whether recursion counts as looping depends on which exact definition you use, but it's probably as close as you'll get.



                        I don't know whether most JVMs do tail-recursion these days... if not you'll get the eponymous stack overflow for suitably long strings, of course.






                        share|improve this answer























                        • No, tail recursion will probably be in Java 7, but it's not widespread yet. This simple, direct tail recursion could be translated to a loop at compile time, but the Java 7 stuff is actually built-in to the JVM to handle chaining through different methods.
                          – erickson
                          Nov 10 '08 at 20:11






                        • 3




                          You'd be more likely to get tail recursion if your method returned a call to itself (including a running total parameter), rather than returning the result of performing an addition.
                          – Stephen Denne
                          Mar 20 '09 at 10:56













                        up vote
                        12
                        down vote










                        up vote
                        12
                        down vote









                        Okay, inspired by Yonatan's solution, here's one which is purely recursive - the only library methods used are length() and charAt(), neither of which do any looping:



                        public static int countOccurrences(String haystack, char needle)
                        {
                        return countOccurrences(haystack, needle, 0);
                        }

                        private static int countOccurrences(String haystack, char needle, int index)
                        {
                        if (index >= haystack.length())
                        {
                        return 0;
                        }

                        int contribution = haystack.charAt(index) == needle ? 1 : 0;
                        return contribution + countOccurrences(haystack, needle, index+1);
                        }


                        Whether recursion counts as looping depends on which exact definition you use, but it's probably as close as you'll get.



                        I don't know whether most JVMs do tail-recursion these days... if not you'll get the eponymous stack overflow for suitably long strings, of course.






                        share|improve this answer














                        Okay, inspired by Yonatan's solution, here's one which is purely recursive - the only library methods used are length() and charAt(), neither of which do any looping:



                        public static int countOccurrences(String haystack, char needle)
                        {
                        return countOccurrences(haystack, needle, 0);
                        }

                        private static int countOccurrences(String haystack, char needle, int index)
                        {
                        if (index >= haystack.length())
                        {
                        return 0;
                        }

                        int contribution = haystack.charAt(index) == needle ? 1 : 0;
                        return contribution + countOccurrences(haystack, needle, index+1);
                        }


                        Whether recursion counts as looping depends on which exact definition you use, but it's probably as close as you'll get.



                        I don't know whether most JVMs do tail-recursion these days... if not you'll get the eponymous stack overflow for suitably long strings, of course.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Nov 5 '15 at 17:10









                        oshai

                        7,2391663103




                        7,2391663103










                        answered Nov 9 '08 at 18:06









                        Jon Skeet

                        1073k67378598393




                        1073k67378598393












                        • No, tail recursion will probably be in Java 7, but it's not widespread yet. This simple, direct tail recursion could be translated to a loop at compile time, but the Java 7 stuff is actually built-in to the JVM to handle chaining through different methods.
                          – erickson
                          Nov 10 '08 at 20:11






                        • 3




                          You'd be more likely to get tail recursion if your method returned a call to itself (including a running total parameter), rather than returning the result of performing an addition.
                          – Stephen Denne
                          Mar 20 '09 at 10:56


















                        • No, tail recursion will probably be in Java 7, but it's not widespread yet. This simple, direct tail recursion could be translated to a loop at compile time, but the Java 7 stuff is actually built-in to the JVM to handle chaining through different methods.
                          – erickson
                          Nov 10 '08 at 20:11






                        • 3




                          You'd be more likely to get tail recursion if your method returned a call to itself (including a running total parameter), rather than returning the result of performing an addition.
                          – Stephen Denne
                          Mar 20 '09 at 10:56
















                        No, tail recursion will probably be in Java 7, but it's not widespread yet. This simple, direct tail recursion could be translated to a loop at compile time, but the Java 7 stuff is actually built-in to the JVM to handle chaining through different methods.
                        – erickson
                        Nov 10 '08 at 20:11




                        No, tail recursion will probably be in Java 7, but it's not widespread yet. This simple, direct tail recursion could be translated to a loop at compile time, but the Java 7 stuff is actually built-in to the JVM to handle chaining through different methods.
                        – erickson
                        Nov 10 '08 at 20:11




                        3




                        3




                        You'd be more likely to get tail recursion if your method returned a call to itself (including a running total parameter), rather than returning the result of performing an addition.
                        – Stephen Denne
                        Mar 20 '09 at 10:56




                        You'd be more likely to get tail recursion if your method returned a call to itself (including a running total parameter), rather than returning the result of performing an addition.
                        – Stephen Denne
                        Mar 20 '09 at 10:56










                        up vote
                        11
                        down vote













                        Inspired by Jon Skeet, a non-loop version that wont blow your stack. Also useful starting point if you want to use the fork-join framework.



                        public static int countOccurrences(CharSequeunce haystack, char needle) {
                        return countOccurrences(haystack, needle, 0, haystack.length);
                        }

                        // Alternatively String.substring/subsequence use to be relatively efficient
                        // on most Java library implementations, but isn't any more [2013].
                        private static int countOccurrences(
                        CharSequence haystack, char needle, int start, int end
                        ) {
                        if (start == end) {
                        return 0;
                        } else if (start+1 == end) {
                        return haystack.charAt(start) == needle ? 1 : 0;
                        } else {
                        int mid = (end+start)>>>1; // Watch for integer overflow...
                        return
                        countOccurrences(haystack, needle, start, mid) +
                        countOccurrences(haystack, needle, mid, end);
                        }
                        }


                        (Disclaimer: Not tested, not compiled, not sensible.)



                        Perhaps the best (single-threaded, no surrogate-pair support) way to write it:



                        public static int countOccurrences(String haystack, char needle) {
                        int count = 0;
                        for (char c : haystack.toCharArray()) {
                        if (c == needle) {
                        ++count;
                        }
                        }
                        return count;
                        }





                        share|improve this answer



























                          up vote
                          11
                          down vote













                          Inspired by Jon Skeet, a non-loop version that wont blow your stack. Also useful starting point if you want to use the fork-join framework.



                          public static int countOccurrences(CharSequeunce haystack, char needle) {
                          return countOccurrences(haystack, needle, 0, haystack.length);
                          }

                          // Alternatively String.substring/subsequence use to be relatively efficient
                          // on most Java library implementations, but isn't any more [2013].
                          private static int countOccurrences(
                          CharSequence haystack, char needle, int start, int end
                          ) {
                          if (start == end) {
                          return 0;
                          } else if (start+1 == end) {
                          return haystack.charAt(start) == needle ? 1 : 0;
                          } else {
                          int mid = (end+start)>>>1; // Watch for integer overflow...
                          return
                          countOccurrences(haystack, needle, start, mid) +
                          countOccurrences(haystack, needle, mid, end);
                          }
                          }


                          (Disclaimer: Not tested, not compiled, not sensible.)



                          Perhaps the best (single-threaded, no surrogate-pair support) way to write it:



                          public static int countOccurrences(String haystack, char needle) {
                          int count = 0;
                          for (char c : haystack.toCharArray()) {
                          if (c == needle) {
                          ++count;
                          }
                          }
                          return count;
                          }





                          share|improve this answer

























                            up vote
                            11
                            down vote










                            up vote
                            11
                            down vote









                            Inspired by Jon Skeet, a non-loop version that wont blow your stack. Also useful starting point if you want to use the fork-join framework.



                            public static int countOccurrences(CharSequeunce haystack, char needle) {
                            return countOccurrences(haystack, needle, 0, haystack.length);
                            }

                            // Alternatively String.substring/subsequence use to be relatively efficient
                            // on most Java library implementations, but isn't any more [2013].
                            private static int countOccurrences(
                            CharSequence haystack, char needle, int start, int end
                            ) {
                            if (start == end) {
                            return 0;
                            } else if (start+1 == end) {
                            return haystack.charAt(start) == needle ? 1 : 0;
                            } else {
                            int mid = (end+start)>>>1; // Watch for integer overflow...
                            return
                            countOccurrences(haystack, needle, start, mid) +
                            countOccurrences(haystack, needle, mid, end);
                            }
                            }


                            (Disclaimer: Not tested, not compiled, not sensible.)



                            Perhaps the best (single-threaded, no surrogate-pair support) way to write it:



                            public static int countOccurrences(String haystack, char needle) {
                            int count = 0;
                            for (char c : haystack.toCharArray()) {
                            if (c == needle) {
                            ++count;
                            }
                            }
                            return count;
                            }





                            share|improve this answer














                            Inspired by Jon Skeet, a non-loop version that wont blow your stack. Also useful starting point if you want to use the fork-join framework.



                            public static int countOccurrences(CharSequeunce haystack, char needle) {
                            return countOccurrences(haystack, needle, 0, haystack.length);
                            }

                            // Alternatively String.substring/subsequence use to be relatively efficient
                            // on most Java library implementations, but isn't any more [2013].
                            private static int countOccurrences(
                            CharSequence haystack, char needle, int start, int end
                            ) {
                            if (start == end) {
                            return 0;
                            } else if (start+1 == end) {
                            return haystack.charAt(start) == needle ? 1 : 0;
                            } else {
                            int mid = (end+start)>>>1; // Watch for integer overflow...
                            return
                            countOccurrences(haystack, needle, start, mid) +
                            countOccurrences(haystack, needle, mid, end);
                            }
                            }


                            (Disclaimer: Not tested, not compiled, not sensible.)



                            Perhaps the best (single-threaded, no surrogate-pair support) way to write it:



                            public static int countOccurrences(String haystack, char needle) {
                            int count = 0;
                            for (char c : haystack.toCharArray()) {
                            if (c == needle) {
                            ++count;
                            }
                            }
                            return count;
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Sep 17 '13 at 12:30

























                            answered Nov 11 '08 at 14:20









                            Tom Hawtin - tackline

                            125k28179266




                            125k28179266






















                                up vote
                                9
                                down vote













                                Not sure about the efficiency of this, but it's the shortest code I could write without bringing in 3rd party libs:



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





                                share|improve this answer



















                                • 4




                                  To also count occurences at the end of the string you will have to call split with a negative limit argument like this: return (content.split(target, -1).length - 1);. By default occurences at the end of the string are omitted in the Array resulting from split(). See the Doku
                                  – vlz
                                  May 4 '14 at 12:08

















                                up vote
                                9
                                down vote













                                Not sure about the efficiency of this, but it's the shortest code I could write without bringing in 3rd party libs:



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





                                share|improve this answer



















                                • 4




                                  To also count occurences at the end of the string you will have to call split with a negative limit argument like this: return (content.split(target, -1).length - 1);. By default occurences at the end of the string are omitted in the Array resulting from split(). See the Doku
                                  – vlz
                                  May 4 '14 at 12:08















                                up vote
                                9
                                down vote










                                up vote
                                9
                                down vote









                                Not sure about the efficiency of this, but it's the shortest code I could write without bringing in 3rd party libs:



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





                                share|improve this answer














                                Not sure about the efficiency of this, but it's the shortest code I could write without bringing in 3rd party libs:



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






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Aug 12 '13 at 16:50

























                                answered Jan 11 '13 at 14:23









                                KannedFarU

                                12017




                                12017








                                • 4




                                  To also count occurences at the end of the string you will have to call split with a negative limit argument like this: return (content.split(target, -1).length - 1);. By default occurences at the end of the string are omitted in the Array resulting from split(). See the Doku
                                  – vlz
                                  May 4 '14 at 12:08
















                                • 4




                                  To also count occurences at the end of the string you will have to call split with a negative limit argument like this: return (content.split(target, -1).length - 1);. By default occurences at the end of the string are omitted in the Array resulting from split(). See the Doku
                                  – vlz
                                  May 4 '14 at 12:08










                                4




                                4




                                To also count occurences at the end of the string you will have to call split with a negative limit argument like this: return (content.split(target, -1).length - 1);. By default occurences at the end of the string are omitted in the Array resulting from split(). See the Doku
                                – vlz
                                May 4 '14 at 12:08






                                To also count occurences at the end of the string you will have to call split with a negative limit argument like this: return (content.split(target, -1).length - 1);. By default occurences at the end of the string are omitted in the Array resulting from split(). See the Doku
                                – vlz
                                May 4 '14 at 12:08












                                up vote
                                9
                                down vote













                                With java-8 you could also use streams to achieve this. Obviously there is an iteration behind the scenes, but you don't have to write it explicitly!



                                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





                                share|improve this answer





















                                • Using .codePoints() instead of .chars() would then support any Unicode value (including those requiring surrogate pairs)
                                  – Luke Usherwood
                                  Aug 14 '14 at 14:40















                                up vote
                                9
                                down vote













                                With java-8 you could also use streams to achieve this. Obviously there is an iteration behind the scenes, but you don't have to write it explicitly!



                                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





                                share|improve this answer





















                                • Using .codePoints() instead of .chars() would then support any Unicode value (including those requiring surrogate pairs)
                                  – Luke Usherwood
                                  Aug 14 '14 at 14:40













                                up vote
                                9
                                down vote










                                up vote
                                9
                                down vote









                                With java-8 you could also use streams to achieve this. Obviously there is an iteration behind the scenes, but you don't have to write it explicitly!



                                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





                                share|improve this answer












                                With java-8 you could also use streams to achieve this. Obviously there is an iteration behind the scenes, but you don't have to write it explicitly!



                                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






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered May 26 '14 at 16:39









                                Alexis C.

                                66.8k12127155




                                66.8k12127155












                                • Using .codePoints() instead of .chars() would then support any Unicode value (including those requiring surrogate pairs)
                                  – Luke Usherwood
                                  Aug 14 '14 at 14:40


















                                • Using .codePoints() instead of .chars() would then support any Unicode value (including those requiring surrogate pairs)
                                  – Luke Usherwood
                                  Aug 14 '14 at 14:40
















                                Using .codePoints() instead of .chars() would then support any Unicode value (including those requiring surrogate pairs)
                                – Luke Usherwood
                                Aug 14 '14 at 14:40




                                Using .codePoints() instead of .chars() would then support any Unicode value (including those requiring surrogate pairs)
                                – Luke Usherwood
                                Aug 14 '14 at 14:40










                                up vote
                                7
                                down vote













                                Complete sample:



                                public class CharacterCounter
                                {

                                public static int countOccurrences(String find, String string)
                                {
                                int count = 0;
                                int indexOf = 0;

                                while (indexOf > -1)
                                {
                                indexOf = string.indexOf(find, indexOf + 1);
                                if (indexOf > -1)
                                count++;
                                }

                                return count;
                                }
                                }


                                Call:



                                int occurrences = CharacterCounter.countOccurrences("l", "Hello World.");
                                System.out.println(occurrences); // 3





                                share|improve this answer





















                                • wrong code its not working when i try int occurrences = CharacterCounter.countOccurrences("1", "101"); System.out.println(occurrences); // 1
                                  – jayesh
                                  Jan 20 '14 at 6:32












                                • I commit a fix for the code that works with the same logic
                                  – MaanooAk
                                  Jul 27 '17 at 7:06















                                up vote
                                7
                                down vote













                                Complete sample:



                                public class CharacterCounter
                                {

                                public static int countOccurrences(String find, String string)
                                {
                                int count = 0;
                                int indexOf = 0;

                                while (indexOf > -1)
                                {
                                indexOf = string.indexOf(find, indexOf + 1);
                                if (indexOf > -1)
                                count++;
                                }

                                return count;
                                }
                                }


                                Call:



                                int occurrences = CharacterCounter.countOccurrences("l", "Hello World.");
                                System.out.println(occurrences); // 3





                                share|improve this answer





















                                • wrong code its not working when i try int occurrences = CharacterCounter.countOccurrences("1", "101"); System.out.println(occurrences); // 1
                                  – jayesh
                                  Jan 20 '14 at 6:32












                                • I commit a fix for the code that works with the same logic
                                  – MaanooAk
                                  Jul 27 '17 at 7:06













                                up vote
                                7
                                down vote










                                up vote
                                7
                                down vote









                                Complete sample:



                                public class CharacterCounter
                                {

                                public static int countOccurrences(String find, String string)
                                {
                                int count = 0;
                                int indexOf = 0;

                                while (indexOf > -1)
                                {
                                indexOf = string.indexOf(find, indexOf + 1);
                                if (indexOf > -1)
                                count++;
                                }

                                return count;
                                }
                                }


                                Call:



                                int occurrences = CharacterCounter.countOccurrences("l", "Hello World.");
                                System.out.println(occurrences); // 3





                                share|improve this answer












                                Complete sample:



                                public class CharacterCounter
                                {

                                public static int countOccurrences(String find, String string)
                                {
                                int count = 0;
                                int indexOf = 0;

                                while (indexOf > -1)
                                {
                                indexOf = string.indexOf(find, indexOf + 1);
                                if (indexOf > -1)
                                count++;
                                }

                                return count;
                                }
                                }


                                Call:



                                int occurrences = CharacterCounter.countOccurrences("l", "Hello World.");
                                System.out.println(occurrences); // 3






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Mar 3 '12 at 17:54









                                Benny Neugebauer

                                26.5k15142149




                                26.5k15142149












                                • wrong code its not working when i try int occurrences = CharacterCounter.countOccurrences("1", "101"); System.out.println(occurrences); // 1
                                  – jayesh
                                  Jan 20 '14 at 6:32












                                • I commit a fix for the code that works with the same logic
                                  – MaanooAk
                                  Jul 27 '17 at 7:06


















                                • wrong code its not working when i try int occurrences = CharacterCounter.countOccurrences("1", "101"); System.out.println(occurrences); // 1
                                  – jayesh
                                  Jan 20 '14 at 6:32












                                • I commit a fix for the code that works with the same logic
                                  – MaanooAk
                                  Jul 27 '17 at 7:06
















                                wrong code its not working when i try int occurrences = CharacterCounter.countOccurrences("1", "101"); System.out.println(occurrences); // 1
                                – jayesh
                                Jan 20 '14 at 6:32






                                wrong code its not working when i try int occurrences = CharacterCounter.countOccurrences("1", "101"); System.out.println(occurrences); // 1
                                – jayesh
                                Jan 20 '14 at 6:32














                                I commit a fix for the code that works with the same logic
                                – MaanooAk
                                Jul 27 '17 at 7:06




                                I commit a fix for the code that works with the same logic
                                – MaanooAk
                                Jul 27 '17 at 7:06










                                up vote
                                5
                                down vote













                                In case you're using Spring framework, you might also use "StringUtils" class.
                                The method would be "countOccurrencesOf".






                                share|improve this answer



























                                  up vote
                                  5
                                  down vote













                                  In case you're using Spring framework, you might also use "StringUtils" class.
                                  The method would be "countOccurrencesOf".






                                  share|improve this answer

























                                    up vote
                                    5
                                    down vote










                                    up vote
                                    5
                                    down vote









                                    In case you're using Spring framework, you might also use "StringUtils" class.
                                    The method would be "countOccurrencesOf".






                                    share|improve this answer














                                    In case you're using Spring framework, you might also use "StringUtils" class.
                                    The method would be "countOccurrencesOf".







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Apr 15 '15 at 20:21









                                    Michal Kordas

                                    5,04912553




                                    5,04912553










                                    answered Feb 24 '11 at 11:21









                                    user496208

                                    6912




                                    6912






















                                        up vote
                                        5
                                        down vote













                                        The simplest way to get the answer is as follow:



                                        public static void main(String args) {
                                        String string = "a.b.c.d";
                                        String splitArray = string.split("\.");
                                        System.out.println("No of . chars is : " + splitArray.length-1);
                                        }





                                        share|improve this answer





















                                        • This snippet does not return the correct amount of dots for a given input "a.b.c."
                                          – dekaru
                                          Nov 6 at 23:09










                                        • @dekaru Could you please paste your sting in the comment so that we can take a look.
                                          – Amar Magar
                                          Nov 14 at 7:19















                                        up vote
                                        5
                                        down vote













                                        The simplest way to get the answer is as follow:



                                        public static void main(String args) {
                                        String string = "a.b.c.d";
                                        String splitArray = string.split("\.");
                                        System.out.println("No of . chars is : " + splitArray.length-1);
                                        }





                                        share|improve this answer





















                                        • This snippet does not return the correct amount of dots for a given input "a.b.c."
                                          – dekaru
                                          Nov 6 at 23:09










                                        • @dekaru Could you please paste your sting in the comment so that we can take a look.
                                          – Amar Magar
                                          Nov 14 at 7:19













                                        up vote
                                        5
                                        down vote










                                        up vote
                                        5
                                        down vote









                                        The simplest way to get the answer is as follow:



                                        public static void main(String args) {
                                        String string = "a.b.c.d";
                                        String splitArray = string.split("\.");
                                        System.out.println("No of . chars is : " + splitArray.length-1);
                                        }





                                        share|improve this answer












                                        The simplest way to get the answer is as follow:



                                        public static void main(String args) {
                                        String string = "a.b.c.d";
                                        String splitArray = string.split("\.");
                                        System.out.println("No of . chars is : " + splitArray.length-1);
                                        }






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered May 17 '17 at 9:14









                                        Amar Magar

                                        411612




                                        411612












                                        • This snippet does not return the correct amount of dots for a given input "a.b.c."
                                          – dekaru
                                          Nov 6 at 23:09










                                        • @dekaru Could you please paste your sting in the comment so that we can take a look.
                                          – Amar Magar
                                          Nov 14 at 7:19


















                                        • This snippet does not return the correct amount of dots for a given input "a.b.c."
                                          – dekaru
                                          Nov 6 at 23:09










                                        • @dekaru Could you please paste your sting in the comment so that we can take a look.
                                          – Amar Magar
                                          Nov 14 at 7:19
















                                        This snippet does not return the correct amount of dots for a given input "a.b.c."
                                        – dekaru
                                        Nov 6 at 23:09




                                        This snippet does not return the correct amount of dots for a given input "a.b.c."
                                        – dekaru
                                        Nov 6 at 23:09












                                        @dekaru Could you please paste your sting in the comment so that we can take a look.
                                        – Amar Magar
                                        Nov 14 at 7:19




                                        @dekaru Could you please paste your sting in the comment so that we can take a look.
                                        – Amar Magar
                                        Nov 14 at 7:19










                                        up vote
                                        5
                                        down vote













                                        Also possible to use reduce in Java 8 to solve this problem:



                                        int res = "abdsd3$asda$asasdd$sadas".chars().reduce(0, (a, c) -> a + (c == '$' ? 1 : 0));
                                        System.out.println(res);


                                        Output:



                                        3





                                        share|improve this answer

























                                          up vote
                                          5
                                          down vote













                                          Also possible to use reduce in Java 8 to solve this problem:



                                          int res = "abdsd3$asda$asasdd$sadas".chars().reduce(0, (a, c) -> a + (c == '$' ? 1 : 0));
                                          System.out.println(res);


                                          Output:



                                          3





                                          share|improve this answer























                                            up vote
                                            5
                                            down vote










                                            up vote
                                            5
                                            down vote









                                            Also possible to use reduce in Java 8 to solve this problem:



                                            int res = "abdsd3$asda$asasdd$sadas".chars().reduce(0, (a, c) -> a + (c == '$' ? 1 : 0));
                                            System.out.println(res);


                                            Output:



                                            3





                                            share|improve this answer












                                            Also possible to use reduce in Java 8 to solve this problem:



                                            int res = "abdsd3$asda$asasdd$sadas".chars().reduce(0, (a, c) -> a + (c == '$' ? 1 : 0));
                                            System.out.println(res);


                                            Output:



                                            3






                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered May 24 '17 at 14:05









                                            gil.fernandes

                                            5,43121435




                                            5,43121435






















                                                up vote
                                                4
                                                down vote













                                                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





                                                share|improve this answer























                                                • This answer is essentially the same as stackoverflow.com/a/275979/577167
                                                  – Joulukuusi
                                                  Nov 14 '12 at 23:34















                                                up vote
                                                4
                                                down vote













                                                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





                                                share|improve this answer























                                                • This answer is essentially the same as stackoverflow.com/a/275979/577167
                                                  – Joulukuusi
                                                  Nov 14 '12 at 23:34













                                                up vote
                                                4
                                                down vote










                                                up vote
                                                4
                                                down vote









                                                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





                                                share|improve this answer














                                                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






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Nov 14 '12 at 23:33









                                                Michael Petrotta

                                                51.3k12127170




                                                51.3k12127170










                                                answered Nov 14 '12 at 23:11









                                                kassim

                                                411




                                                411












                                                • This answer is essentially the same as stackoverflow.com/a/275979/577167
                                                  – Joulukuusi
                                                  Nov 14 '12 at 23:34


















                                                • This answer is essentially the same as stackoverflow.com/a/275979/577167
                                                  – Joulukuusi
                                                  Nov 14 '12 at 23:34
















                                                This answer is essentially the same as stackoverflow.com/a/275979/577167
                                                – Joulukuusi
                                                Nov 14 '12 at 23:34




                                                This answer is essentially the same as stackoverflow.com/a/275979/577167
                                                – Joulukuusi
                                                Nov 14 '12 at 23:34










                                                up vote
                                                4
                                                down vote













                                                You can use the split() function in just one line code



                                                int noOccurence=string.split("#").length-1;





                                                share|improve this answer























                                                • Split really creates the array of strings, which consumes much time.
                                                  – Palec
                                                  May 19 '16 at 17:03










                                                • You're right, that's a true concern. In another way it avoids bringing a third-party lib in your project (if not yet done). It depends on what you want to do and what is the performance expectation.
                                                  – Benj
                                                  Jun 14 '16 at 7:23






                                                • 2




                                                  This solution will NOT include the trailing empty hits, because the argument limit is set to zero in this overloaded split method call. An example: "1##2#3#####".split("#") will only yield an array of size 4 ([0:"1";1:""; 2:"2"; 3:"3"]) instead size 9 ([0:"1"; 1:""; 2:"2"; 3:"3"; 4:""; 5:""; 6:""; 7:""; 8:""]).
                                                  – klaar
                                                  Aug 31 '16 at 15:05

















                                                up vote
                                                4
                                                down vote













                                                You can use the split() function in just one line code



                                                int noOccurence=string.split("#").length-1;





                                                share|improve this answer























                                                • Split really creates the array of strings, which consumes much time.
                                                  – Palec
                                                  May 19 '16 at 17:03










                                                • You're right, that's a true concern. In another way it avoids bringing a third-party lib in your project (if not yet done). It depends on what you want to do and what is the performance expectation.
                                                  – Benj
                                                  Jun 14 '16 at 7:23






                                                • 2




                                                  This solution will NOT include the trailing empty hits, because the argument limit is set to zero in this overloaded split method call. An example: "1##2#3#####".split("#") will only yield an array of size 4 ([0:"1";1:""; 2:"2"; 3:"3"]) instead size 9 ([0:"1"; 1:""; 2:"2"; 3:"3"; 4:""; 5:""; 6:""; 7:""; 8:""]).
                                                  – klaar
                                                  Aug 31 '16 at 15:05















                                                up vote
                                                4
                                                down vote










                                                up vote
                                                4
                                                down vote









                                                You can use the split() function in just one line code



                                                int noOccurence=string.split("#").length-1;





                                                share|improve this answer














                                                You can use the split() function in just one line code



                                                int noOccurence=string.split("#").length-1;






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Jul 22 '16 at 9:30









                                                Radouane ROUFID

                                                6,67042551




                                                6,67042551










                                                answered May 19 '16 at 7:59









                                                user3322553

                                                1398




                                                1398












                                                • Split really creates the array of strings, which consumes much time.
                                                  – Palec
                                                  May 19 '16 at 17:03










                                                • You're right, that's a true concern. In another way it avoids bringing a third-party lib in your project (if not yet done). It depends on what you want to do and what is the performance expectation.
                                                  – Benj
                                                  Jun 14 '16 at 7:23






                                                • 2




                                                  This solution will NOT include the trailing empty hits, because the argument limit is set to zero in this overloaded split method call. An example: "1##2#3#####".split("#") will only yield an array of size 4 ([0:"1";1:""; 2:"2"; 3:"3"]) instead size 9 ([0:"1"; 1:""; 2:"2"; 3:"3"; 4:""; 5:""; 6:""; 7:""; 8:""]).
                                                  – klaar
                                                  Aug 31 '16 at 15:05




















                                                • Split really creates the array of strings, which consumes much time.
                                                  – Palec
                                                  May 19 '16 at 17:03










                                                • You're right, that's a true concern. In another way it avoids bringing a third-party lib in your project (if not yet done). It depends on what you want to do and what is the performance expectation.
                                                  – Benj
                                                  Jun 14 '16 at 7:23






                                                • 2




                                                  This solution will NOT include the trailing empty hits, because the argument limit is set to zero in this overloaded split method call. An example: "1##2#3#####".split("#") will only yield an array of size 4 ([0:"1";1:""; 2:"2"; 3:"3"]) instead size 9 ([0:"1"; 1:""; 2:"2"; 3:"3"; 4:""; 5:""; 6:""; 7:""; 8:""]).
                                                  – klaar
                                                  Aug 31 '16 at 15:05


















                                                Split really creates the array of strings, which consumes much time.
                                                – Palec
                                                May 19 '16 at 17:03




                                                Split really creates the array of strings, which consumes much time.
                                                – Palec
                                                May 19 '16 at 17:03












                                                You're right, that's a true concern. In another way it avoids bringing a third-party lib in your project (if not yet done). It depends on what you want to do and what is the performance expectation.
                                                – Benj
                                                Jun 14 '16 at 7:23




                                                You're right, that's a true concern. In another way it avoids bringing a third-party lib in your project (if not yet done). It depends on what you want to do and what is the performance expectation.
                                                – Benj
                                                Jun 14 '16 at 7:23




                                                2




                                                2




                                                This solution will NOT include the trailing empty hits, because the argument limit is set to zero in this overloaded split method call. An example: "1##2#3#####".split("#") will only yield an array of size 4 ([0:"1";1:""; 2:"2"; 3:"3"]) instead size 9 ([0:"1"; 1:""; 2:"2"; 3:"3"; 4:""; 5:""; 6:""; 7:""; 8:""]).
                                                – klaar
                                                Aug 31 '16 at 15:05






                                                This solution will NOT include the trailing empty hits, because the argument limit is set to zero in this overloaded split method call. An example: "1##2#3#####".split("#") will only yield an array of size 4 ([0:"1";1:""; 2:"2"; 3:"3"]) instead size 9 ([0:"1"; 1:""; 2:"2"; 3:"3"; 4:""; 5:""; 6:""; 7:""; 8:""]).
                                                – klaar
                                                Aug 31 '16 at 15:05












                                                up vote
                                                3
                                                down vote













                                                While methods can hide it, there is no way to count without a loop (or recursion). You want to use a char for performance reasons though.



                                                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;
                                                }


                                                Using replaceAll (that is RE) does not sound like the best way to go.






                                                share|improve this answer





















                                                • I think this is the most elegant solution. Why did you use toCharArray and not charAt directly?
                                                  – Panayotis
                                                  May 31 '17 at 8:29












                                                • Looping with charAt at least used to be slower. Might depend on the platform, too. The only way to really find out would be to measure the difference.
                                                  – tcurdt
                                                  May 31 '17 at 14:00















                                                up vote
                                                3
                                                down vote













                                                While methods can hide it, there is no way to count without a loop (or recursion). You want to use a char for performance reasons though.



                                                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;
                                                }


                                                Using replaceAll (that is RE) does not sound like the best way to go.






                                                share|improve this answer





















                                                • I think this is the most elegant solution. Why did you use toCharArray and not charAt directly?
                                                  – Panayotis
                                                  May 31 '17 at 8:29












                                                • Looping with charAt at least used to be slower. Might depend on the platform, too. The only way to really find out would be to measure the difference.
                                                  – tcurdt
                                                  May 31 '17 at 14:00













                                                up vote
                                                3
                                                down vote










                                                up vote
                                                3
                                                down vote









                                                While methods can hide it, there is no way to count without a loop (or recursion). You want to use a char for performance reasons though.



                                                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;
                                                }


                                                Using replaceAll (that is RE) does not sound like the best way to go.






                                                share|improve this answer












                                                While methods can hide it, there is no way to count without a loop (or recursion). You want to use a char for performance reasons though.



                                                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;
                                                }


                                                Using replaceAll (that is RE) does not sound like the best way to go.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Nov 9 '08 at 18:19









                                                tcurdt

                                                8,00374659




                                                8,00374659












                                                • I think this is the most elegant solution. Why did you use toCharArray and not charAt directly?
                                                  – Panayotis
                                                  May 31 '17 at 8:29












                                                • Looping with charAt at least used to be slower. Might depend on the platform, too. The only way to really find out would be to measure the difference.
                                                  – tcurdt
                                                  May 31 '17 at 14:00


















                                                • I think this is the most elegant solution. Why did you use toCharArray and not charAt directly?
                                                  – Panayotis
                                                  May 31 '17 at 8:29












                                                • Looping with charAt at least used to be slower. Might depend on the platform, too. The only way to really find out would be to measure the difference.
                                                  – tcurdt
                                                  May 31 '17 at 14:00
















                                                I think this is the most elegant solution. Why did you use toCharArray and not charAt directly?
                                                – Panayotis
                                                May 31 '17 at 8:29






                                                I think this is the most elegant solution. Why did you use toCharArray and not charAt directly?
                                                – Panayotis
                                                May 31 '17 at 8:29














                                                Looping with charAt at least used to be slower. Might depend on the platform, too. The only way to really find out would be to measure the difference.
                                                – tcurdt
                                                May 31 '17 at 14:00




                                                Looping with charAt at least used to be slower. Might depend on the platform, too. The only way to really find out would be to measure the difference.
                                                – tcurdt
                                                May 31 '17 at 14:00










                                                up vote
                                                3
                                                down vote













                                                public 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;
                                                }





                                                share|improve this answer

























                                                  up vote
                                                  3
                                                  down vote













                                                  public 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;
                                                  }





                                                  share|improve this answer























                                                    up vote
                                                    3
                                                    down vote










                                                    up vote
                                                    3
                                                    down vote









                                                    public 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;
                                                    }





                                                    share|improve this answer












                                                    public 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;
                                                    }






                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Jun 7 '11 at 15:29









                                                    Hardest

                                                    17325




                                                    17325






















                                                        up vote
                                                        2
                                                        down vote













                                                        Somewhere in the code, something has to loop. The only way around this is a complete unrolling of the loop:



                                                        int numDots = 0;
                                                        if (s.charAt(0) == '.') {
                                                        numDots++;
                                                        }

                                                        if (s.charAt(1) == '.') {
                                                        numDots++;
                                                        }


                                                        if (s.charAt(2) == '.') {
                                                        numDots++;
                                                        }


                                                        ...etc, but then you're the one doing the loop, manually, in the source editor - instead of the computer that will run it. See the pseudocode:



                                                        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





                                                        share|improve this answer

























                                                          up vote
                                                          2
                                                          down vote













                                                          Somewhere in the code, something has to loop. The only way around this is a complete unrolling of the loop:



                                                          int numDots = 0;
                                                          if (s.charAt(0) == '.') {
                                                          numDots++;
                                                          }

                                                          if (s.charAt(1) == '.') {
                                                          numDots++;
                                                          }


                                                          if (s.charAt(2) == '.') {
                                                          numDots++;
                                                          }


                                                          ...etc, but then you're the one doing the loop, manually, in the source editor - instead of the computer that will run it. See the pseudocode:



                                                          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





                                                          share|improve this answer























                                                            up vote
                                                            2
                                                            down vote










                                                            up vote
                                                            2
                                                            down vote









                                                            Somewhere in the code, something has to loop. The only way around this is a complete unrolling of the loop:



                                                            int numDots = 0;
                                                            if (s.charAt(0) == '.') {
                                                            numDots++;
                                                            }

                                                            if (s.charAt(1) == '.') {
                                                            numDots++;
                                                            }


                                                            if (s.charAt(2) == '.') {
                                                            numDots++;
                                                            }


                                                            ...etc, but then you're the one doing the loop, manually, in the source editor - instead of the computer that will run it. See the pseudocode:



                                                            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





                                                            share|improve this answer












                                                            Somewhere in the code, something has to loop. The only way around this is a complete unrolling of the loop:



                                                            int numDots = 0;
                                                            if (s.charAt(0) == '.') {
                                                            numDots++;
                                                            }

                                                            if (s.charAt(1) == '.') {
                                                            numDots++;
                                                            }


                                                            if (s.charAt(2) == '.') {
                                                            numDots++;
                                                            }


                                                            ...etc, but then you're the one doing the loop, manually, in the source editor - instead of the computer that will run it. See the pseudocode:



                                                            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






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Nov 11 '08 at 14:39









                                                            Piskvor

                                                            71.7k41152207




                                                            71.7k41152207






















                                                                up vote
                                                                2
                                                                down vote













                                                                Here is a slightly different style recursion solution:



                                                                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);
                                                                }





                                                                share|improve this answer

























                                                                  up vote
                                                                  2
                                                                  down vote













                                                                  Here is a slightly different style recursion solution:



                                                                  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);
                                                                  }





                                                                  share|improve this answer























                                                                    up vote
                                                                    2
                                                                    down vote










                                                                    up vote
                                                                    2
                                                                    down vote









                                                                    Here is a slightly different style recursion solution:



                                                                    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);
                                                                    }





                                                                    share|improve this answer












                                                                    Here is a slightly different style recursion solution:



                                                                    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);
                                                                    }






                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Mar 20 '09 at 11:25









                                                                    Stephen Denne

                                                                    29.2k93756




                                                                    29.2k93756






















                                                                        up vote
                                                                        2
                                                                        down vote













                                                                        Why not just split on the character and then get the length of the resulting array. array length will always be number of instances + 1. Right?






                                                                        share|improve this answer

























                                                                          up vote
                                                                          2
                                                                          down vote













                                                                          Why not just split on the character and then get the length of the resulting array. array length will always be number of instances + 1. Right?






                                                                          share|improve this answer























                                                                            up vote
                                                                            2
                                                                            down vote










                                                                            up vote
                                                                            2
                                                                            down vote









                                                                            Why not just split on the character and then get the length of the resulting array. array length will always be number of instances + 1. Right?






                                                                            share|improve this answer












                                                                            Why not just split on the character and then get the length of the resulting array. array length will always be number of instances + 1. Right?







                                                                            share|improve this answer












                                                                            share|improve this answer



                                                                            share|improve this answer










                                                                            answered Apr 28 '11 at 4:59









                                                                            Darryl Price

                                                                            2112




                                                                            2112






















                                                                                up vote
                                                                                2
                                                                                down vote













                                                                                The following source code will give you no.of occurrences of a given string in a word entered by user :-



                                                                                import java.util.Scanner;

                                                                                public class CountingOccurences {

                                                                                public static void main(String args) {

                                                                                Scanner inp= new Scanner(System.in);
                                                                                String str;
                                                                                char ch;
                                                                                int count=0;

                                                                                System.out.println("Enter the string:");
                                                                                str=inp.nextLine();

                                                                                while(str.length()>0)
                                                                                {
                                                                                ch=str.charAt(0);
                                                                                int i=0;

                                                                                while(str.charAt(i)==ch)
                                                                                {
                                                                                count =count+i;
                                                                                i++;
                                                                                }

                                                                                str.substring(count);
                                                                                System.out.println(ch);
                                                                                System.out.println(count);
                                                                                }

                                                                                }
                                                                                }





                                                                                share|improve this answer



























                                                                                  up vote
                                                                                  2
                                                                                  down vote













                                                                                  The following source code will give you no.of occurrences of a given string in a word entered by user :-



                                                                                  import java.util.Scanner;

                                                                                  public class CountingOccurences {

                                                                                  public static void main(String args) {

                                                                                  Scanner inp= new Scanner(System.in);
                                                                                  String str;
                                                                                  char ch;
                                                                                  int count=0;

                                                                                  System.out.println("Enter the string:");
                                                                                  str=inp.nextLine();

                                                                                  while(str.length()>0)
                                                                                  {
                                                                                  ch=str.charAt(0);
                                                                                  int i=0;

                                                                                  while(str.charAt(i)==ch)
                                                                                  {
                                                                                  count =count+i;
                                                                                  i++;
                                                                                  }

                                                                                  str.substring(count);
                                                                                  System.out.println(ch);
                                                                                  System.out.println(count);
                                                                                  }

                                                                                  }
                                                                                  }





                                                                                  share|improve this answer

























                                                                                    up vote
                                                                                    2
                                                                                    down vote










                                                                                    up vote
                                                                                    2
                                                                                    down vote









                                                                                    The following source code will give you no.of occurrences of a given string in a word entered by user :-



                                                                                    import java.util.Scanner;

                                                                                    public class CountingOccurences {

                                                                                    public static void main(String args) {

                                                                                    Scanner inp= new Scanner(System.in);
                                                                                    String str;
                                                                                    char ch;
                                                                                    int count=0;

                                                                                    System.out.println("Enter the string:");
                                                                                    str=inp.nextLine();

                                                                                    while(str.length()>0)
                                                                                    {
                                                                                    ch=str.charAt(0);
                                                                                    int i=0;

                                                                                    while(str.charAt(i)==ch)
                                                                                    {
                                                                                    count =count+i;
                                                                                    i++;
                                                                                    }

                                                                                    str.substring(count);
                                                                                    System.out.println(ch);
                                                                                    System.out.println(count);
                                                                                    }

                                                                                    }
                                                                                    }





                                                                                    share|improve this answer














                                                                                    The following source code will give you no.of occurrences of a given string in a word entered by user :-



                                                                                    import java.util.Scanner;

                                                                                    public class CountingOccurences {

                                                                                    public static void main(String args) {

                                                                                    Scanner inp= new Scanner(System.in);
                                                                                    String str;
                                                                                    char ch;
                                                                                    int count=0;

                                                                                    System.out.println("Enter the string:");
                                                                                    str=inp.nextLine();

                                                                                    while(str.length()>0)
                                                                                    {
                                                                                    ch=str.charAt(0);
                                                                                    int i=0;

                                                                                    while(str.charAt(i)==ch)
                                                                                    {
                                                                                    count =count+i;
                                                                                    i++;
                                                                                    }

                                                                                    str.substring(count);
                                                                                    System.out.println(ch);
                                                                                    System.out.println(count);
                                                                                    }

                                                                                    }
                                                                                    }






                                                                                    share|improve this answer














                                                                                    share|improve this answer



                                                                                    share|improve this answer








                                                                                    edited May 2 '13 at 11:17









                                                                                    Salvatorelab

                                                                                    7,92064068




                                                                                    7,92064068










                                                                                    answered May 2 '13 at 10:56









                                                                                    Shubham

                                                                                    10111




                                                                                    10111






















                                                                                        up vote
                                                                                        2
                                                                                        down vote













                                                                                        int count = (line.length() - line.replace("str", "").length())/"str".length();





                                                                                        share|improve this answer



























                                                                                          up vote
                                                                                          2
                                                                                          down vote













                                                                                          int count = (line.length() - line.replace("str", "").length())/"str".length();





                                                                                          share|improve this answer

























                                                                                            up vote
                                                                                            2
                                                                                            down vote










                                                                                            up vote
                                                                                            2
                                                                                            down vote









                                                                                            int count = (line.length() - line.replace("str", "").length())/"str".length();





                                                                                            share|improve this answer














                                                                                            int count = (line.length() - line.replace("str", "").length())/"str".length();






                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited May 7 '14 at 12:29









                                                                                            Not a bug

                                                                                            3,37312562




                                                                                            3,37312562










                                                                                            answered May 7 '14 at 12:03









                                                                                            Shaban

                                                                                            58111




                                                                                            58111






















                                                                                                up vote
                                                                                                2
                                                                                                down vote













                                                                                                Using Eclipse Collections



                                                                                                int count = CharAdapter.adapt("a.b.c.d").count(c -> c == '.');


                                                                                                If you have more than one character to count, you can use a CharBag as follows:



                                                                                                CharBag bag = CharAdapter.adapt("a.b.c.d").toBag();
                                                                                                int count = bag.occurrencesOf('.');


                                                                                                Note: I am a committer for Eclipse Collections.






                                                                                                share|improve this answer

























                                                                                                  up vote
                                                                                                  2
                                                                                                  down vote













                                                                                                  Using Eclipse Collections



                                                                                                  int count = CharAdapter.adapt("a.b.c.d").count(c -> c == '.');


                                                                                                  If you have more than one character to count, you can use a CharBag as follows:



                                                                                                  CharBag bag = CharAdapter.adapt("a.b.c.d").toBag();
                                                                                                  int count = bag.occurrencesOf('.');


                                                                                                  Note: I am a committer for Eclipse Collections.






                                                                                                  share|improve this answer























                                                                                                    up vote
                                                                                                    2
                                                                                                    down vote










                                                                                                    up vote
                                                                                                    2
                                                                                                    down vote









                                                                                                    Using Eclipse Collections



                                                                                                    int count = CharAdapter.adapt("a.b.c.d").count(c -> c == '.');


                                                                                                    If you have more than one character to count, you can use a CharBag as follows:



                                                                                                    CharBag bag = CharAdapter.adapt("a.b.c.d").toBag();
                                                                                                    int count = bag.occurrencesOf('.');


                                                                                                    Note: I am a committer for Eclipse Collections.






                                                                                                    share|improve this answer












                                                                                                    Using Eclipse Collections



                                                                                                    int count = CharAdapter.adapt("a.b.c.d").count(c -> c == '.');


                                                                                                    If you have more than one character to count, you can use a CharBag as follows:



                                                                                                    CharBag bag = CharAdapter.adapt("a.b.c.d").toBag();
                                                                                                    int count = bag.occurrencesOf('.');


                                                                                                    Note: I am a committer for Eclipse Collections.







                                                                                                    share|improve this answer












                                                                                                    share|improve this answer



                                                                                                    share|improve this answer










                                                                                                    answered Jun 23 '17 at 5:40









                                                                                                    Donald Raab

                                                                                                    4,12112029




                                                                                                    4,12112029






















                                                                                                        up vote
                                                                                                        2
                                                                                                        down vote













                                                                                                        Well, with a quite similar task I stumbled upon this Thread.
                                                                                                        I did not see any programming language restriction and since groovy runs on a java vm:
                                                                                                        Here is how I was able to solve my Problem using Groovy.



                                                                                                        "a.b.c.".count(".")


                                                                                                        done.






                                                                                                        share|improve this answer



























                                                                                                          up vote
                                                                                                          2
                                                                                                          down vote













                                                                                                          Well, with a quite similar task I stumbled upon this Thread.
                                                                                                          I did not see any programming language restriction and since groovy runs on a java vm:
                                                                                                          Here is how I was able to solve my Problem using Groovy.



                                                                                                          "a.b.c.".count(".")


                                                                                                          done.






                                                                                                          share|improve this answer

























                                                                                                            up vote
                                                                                                            2
                                                                                                            down vote










                                                                                                            up vote
                                                                                                            2
                                                                                                            down vote









                                                                                                            Well, with a quite similar task I stumbled upon this Thread.
                                                                                                            I did not see any programming language restriction and since groovy runs on a java vm:
                                                                                                            Here is how I was able to solve my Problem using Groovy.



                                                                                                            "a.b.c.".count(".")


                                                                                                            done.






                                                                                                            share|improve this answer














                                                                                                            Well, with a quite similar task I stumbled upon this Thread.
                                                                                                            I did not see any programming language restriction and since groovy runs on a java vm:
                                                                                                            Here is how I was able to solve my Problem using Groovy.



                                                                                                            "a.b.c.".count(".")


                                                                                                            done.







                                                                                                            share|improve this answer














                                                                                                            share|improve this answer



                                                                                                            share|improve this answer








                                                                                                            edited Aug 1 at 19:29









                                                                                                            bdkosher

                                                                                                            3,51722233




                                                                                                            3,51722233










                                                                                                            answered Jan 14 '16 at 23:49









                                                                                                            Christoph Zabinski

                                                                                                            1041315




                                                                                                            1041315






















                                                                                                                1 2
                                                                                                                next

















                                                                                                                draft saved

                                                                                                                draft discarded




















































                                                                                                                Thanks for contributing an answer to Stack Overflow!


                                                                                                                • Please be sure to answer the question. Provide details and share your research!

                                                                                                                But avoid



                                                                                                                • Asking for help, clarification, or responding to other answers.

                                                                                                                • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                To learn more, see our tips on writing great answers.





                                                                                                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                                                                                Please pay close attention to the following guidance:


                                                                                                                • Please be sure to answer the question. Provide details and share your research!

                                                                                                                But avoid



                                                                                                                • Asking for help, clarification, or responding to other answers.

                                                                                                                • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                To learn more, see our tips on writing great answers.




                                                                                                                draft saved


                                                                                                                draft discarded














                                                                                                                StackExchange.ready(
                                                                                                                function () {
                                                                                                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f275944%2fhow-do-i-count-the-number-of-occurrences-of-a-char-in-a-string%23new-answer', 'question_page');
                                                                                                                }
                                                                                                                );

                                                                                                                Post as a guest















                                                                                                                Required, but never shown





















































                                                                                                                Required, but never shown














                                                                                                                Required, but never shown












                                                                                                                Required, but never shown







                                                                                                                Required, but never shown

































                                                                                                                Required, but never shown














                                                                                                                Required, but never shown












                                                                                                                Required, but never shown







                                                                                                                Required, but never shown











                                                                                                                Popular posts from this blog

                                                                                                                Florida Star v. B. J. F.

                                                                                                                Error while running script in elastic search , gateway timeout

                                                                                                                Adding quotations to stringified JSON object values