626

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).

7
  • 1
    Homework? Because otherwise I don't see the requirement to avoid the loop.
    – PhiLho
    Nov 9, 2008 at 16:13
  • 26
    Not averse to a loop so much as looking for an idiomatic one-liner.
    – Bart
    Nov 17, 2008 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, 2015 at 21:31
  • Similar question for strings: stackoverflow.com/questions/767759/…
    – koppor
    Apr 16, 2017 at 19:41
  • Just to point out--I appreciate finding the one-liners, it's fun and (as a true advantage) often easy to remember, but I'd like to point out that a separate method and a loop is better in just about every way--readability and even performance. Most of the "Elegant" solutions below are not going to perform very well because they involve reforming strings/copying memory, whereas a loop that just scanned the string and counted occurrences would be fast and simple. Not that performance should generally be a factor, but don't look at the one-line over a loop and assume it will perform better.
    – Bill K
    May 4, 2017 at 17:41

48 Answers 48

1
2
2

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

    }
}
2
int count = (line.length() - line.replace("str", "").length())/"str".length();
1
 public static int countSubstring(String subStr, String str) {

    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.substring(i).startsWith(subStr)) {
            count++;
        }
    }
    return count;
}
1

Why are you trying to avoid the loop? I mean you can't count the "numberOf" dots without checking every single character of the string, and if you call any function, somehow it will loop. This is, String.replace should do a loop verifying if the string appears so it can replace every single occurrence.

If you're trying to reduce resource usage, you won't do it like that because you're creating a new String just for counting the dots.

Now if we talk about the recursive "enter code here" method, someone said that it will fail due to an OutOfMemmoryException, I think he forgot StackOverflowException.

So my method would be like this (I know it is like the others but, this problem requires the loop):

public static int numberOf(String str,int c) {
    int res=0;
    if(str==null)
        return res;
    for(int i=0;i<str.length();i++)
        if(c==str.charAt(i))
            res++;
    return res;
}
1

I see a lot of tricks and such being used. Now I'm not against beautiful tricks but personally I like to simply call the methods that are meant to do the work, so I've created yet another answer.

Note that if performance is any issue, use Jon Skeet's answer instead. This one is a bit more generalized and therefore slightly more readable in my opinion (and of course, reusable for strings and patterns).

public static int countOccurances(char c, String input) {
    return countOccurancesOfPattern(Pattern.quote(Character.toString(c)), input);
}

public static int countOccurances(String s, String input) {
    return countOccurancesOfPattern(Pattern.quote(s), input);
}

public static int countOccurancesOfPattern(String pattern, String input) {
    Matcher m = Pattern.compile(pattern).matcher(input);
    int count = 0;
    while (m.find()) {
        count++;
    }
    return count;
}
1

a lambda one-liner
w/o the need of an external library.
Creates a map with the count of each character:

Map<Character,Long> counts = "a.b.c.d".codePoints().boxed().collect(
    groupingBy( t -> (char)(int)t, counting() ) );

gets: {a=1, b=1, c=1, d=1, .=3}
the count of a certain character eg. '.' is given over:
counts.get( '.' )

(I also write a lambda solution out of morbid curiosity to find out how slow my solution is, preferably from the man with the 10-line solution.)

0

Try this method:

StringTokenizer stOR = new StringTokenizer(someExpression, "||");
int orCount = stOR.countTokens()-1;
1
  • Downvote from me. It's not returning valid results in all cases, for example if we count 'a' in "a,a,a,a,a" string, it returns 3 instead of 5. May 28, 2015 at 15:05
0

What about below recursive algo.Which is also linear time.

import java.lang.*;
import java.util.*;

class longestSubstr{

public static void main(String[] args){
   String s="ABDEFGABEF";


   int ans=calc(s);

   System.out.println("Max nonrepeating seq= "+ans);

}

public static int calc(String s)
{//s.s
      int n=s.length();
      int max=1;
      if(n==1)
          return 1;
      if(n==2)
      {
          if(s.charAt(0)==s.charAt(1)) return 1;
          else return 2;


      }
      String s1=s;
    String a=s.charAt(n-1)+"";
          s1=s1.replace(a,"");
         // System.out.println(s+" "+(n-2)+" "+s.substring(0,n-1));
         max=Math.max(calc(s.substring(0,n-1)),(calc(s1)+1));


return max;
}


}


</i>
0

Try this code:

package com.java.test;

import java.util.HashMap;
import java.util.Map;

public class TestCuntstring {

    public static void main(String[] args) {

        String name = "Bissssmmayaa";
        char[] ar = new char[name.length()];
        for (int i = 0; i < name.length(); i++) {
            ar[i] = name.charAt(i);
        }
        Map<Character, String> map=new HashMap<Character, String>();
        for (int i = 0; i < ar.length; i++) {
            int count=0;
            for (int j = 0; j < ar.length; j++) {
                if(ar[i]==ar[j]){
                    count++;
                }
            }
            map.put(ar[i], count+" no of times");
        }
        System.out.println(map);
    }

}
0
String[] parts = text.split(".");
int occurances = parts.length - 1;

" It's a great day at O.S.G. Dallas! "
     -- Famous Last Words

Well, it's a case of knowing your Java, especially your basic foundational understanding of the collection classes already available in Java. If you look throughout the entire posting here, there is just about everything short of Stephen Hawking's explanation of the Origin of the Universe, Darwin's paperback on Evolution and Gene Roddenberry's Star Trek cast selection as to why they went with William Shatner short of how to do this quickly and easily...

... need I say anymore?

4
  • 1
    Can you add an explanation to this instead of just posting code? Jul 29, 2017 at 19:10
  • This creates the parts array, which needs to be allocated and later garbage collected. Completely unnecessary overhead. Try doing this in a tight loop.
    – Palec
    Jul 31, 2017 at 11:59
  • 1
    Beside shouldn't it be split("\\.") for splitting at dots? Jan 25, 2018 at 14:58
  • Besides, if the string is "foo." the result will be the same as if the string was "bar"
    – dekaru
    Nov 6, 2018 at 23:08
0

If you want to count the no. of same character in a string 'SELENIUM' or you want to print the unique characters of the string 'SELENIUM'.

public class Count_Characters_In_String{

     public static void main(String []args){

        String s = "SELENIUM";
        System.out.println(s);
        int counter;

       String g = "";

        for( int i=0; i<s.length(); i++ ) { 

        if(g.indexOf(s.charAt(i)) == - 1){
           g=g+s.charAt(i); 
          }

       }
       System.out.println(g + " ");



        for( int i=0; i<g.length(); i++ ) {          
          System.out.print(",");

          System.out.print(s.charAt(i)+ " : ");
          counter=0; 
          for( int j=0; j<s.length(); j++ ) { 

        if( g.charAt(i) == s.charAt(j) ) {
           counter=counter+1;

           }      

          }
          System.out.print(counter); 
       }
     }
}

/******************** OUTPUT **********************/

SELENIUM

SELNIUM

S : 1,E : 2,L : 1,E : 1,N : 1,I : 1,U : 1

0

Using Java 8 and a HashMap without any library for counting all the different chars:

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

use a lambda function which removes all characters to count
the count is the difference of the before-length and after-length

String s = "a.b.c.d";
int count = s.length() - deleteChars.apply( s, "." ).length();  // 3

find deleteChars here


if you have to count the occurrences of more than one character it can be done in one swoop:
eg. for b c and .:

int count = s.length() - deleteChars.apply( s, "bc." ).length();  // 5
0
0

Here is most simple and easy to understand without using arrays, just by using Hashmap. Also it will calculate whitespaces, number of capital chars and small chars, special characters etc.

import java.util.HashMap;
  //The code by muralidharan  
    public class FindChars {
        
        public static void main(String[] args) {
            
            findchars("rererereerererererererere");
        }
        
        public static void findchars(String s){
            
            HashMap<Character,Integer> k=new HashMap<Character,Integer>();
            for(int i=0;i<s.length();i++){
                if(k.containsKey(s.charAt(i))){
                Integer v =k.get(s.charAt(i));
                k.put(s.charAt(i), v+1);
                }else{
                    k.put(s.charAt(i), 1);
                }
                
            }
            System.out.println(k);
            
        }
    
    }

O/P: {r=12, e=13}

second input:

findchars("The world is beautiful and $#$%%%%%%@@@@ is worst");

O/P: { =7, @=4, a=2, b=1, #=1, d=2, $=2, e=2, %=6, f=1, h=1, i=3, l=2, n=1, o=2, r=2, s=3, T=1, t=2, u=2, w=2}

0
 public static String encodeMap(String plainText){
        
        Map<Character,Integer> mapResult=new LinkedHashMap<Character,Integer>();
        String result = "";
        for(int i=0;i<plainText.length();i++){
            if(mapResult.containsKey(plainText.charAt(i))){
            Integer v =mapResult.get(plainText.charAt(i));
            mapResult.put(plainText.charAt(i), v+1);
            }else{
                mapResult.put(plainText.charAt(i), 1);
            }
        }
        
        for(Map.Entry<Character, Integer> t : mapResult.entrySet()) {
            result += String.valueOf(t.getKey())+t.getValue();
        }
        
        return result;
        
    }

 public static void main(String args[]) {
        String  plainText = "aaavvfff";
        System.out.println(encodeMap(plainText)); //a3v2f3  
    }
-1
public static void getCharacter(String str){

        int count[]= new int[256];

        for(int i=0;i<str.length(); i++){


            count[str.charAt(i)]++;

        }
        System.out.println("The ascii values are:"+ Arrays.toString(count));

        //Now display wht character is repeated how many times

        for (int i = 0; i < count.length; i++) {
            if (count[i] > 0)
               System.out.println("Number of " + (char) i + ": " + count[i]);
        }


    }
}
2
  • A blob of code is not a great answer. Maybe try to expand on this with reasoning, explanation, gotchas, etc.
    – user1531971
    Aug 1, 2018 at 19:44
  • Java doesn't use ASCII; char is a UTF-16 code unit. The range is 0..Character.MAX_VALUE. Your algorithm works if the goal is to count occurances of UTF-16 code units. Aug 1, 2018 at 22:47
-3
public class OccurencesInString { public static void main(String[] args) { String str = "NARENDRA AMILINENI"; HashMap occur = new HashMap(); int count =0; String key = null; for(int i=0;i<str.length()-1;i++){ key = String.valueOf(str.charAt(i)); if(occur.containsKey(key)){ count = (Integer)occur.get(key); occur.put(key,++count); }else{ occur.put(key,1); } } System.out.println(occur); } }
2
  • 2
    I see this answer is truncated, so perhaps you don't need the following suggestions. But just to be sure: 1) Don't just paste some code. Explain it a bit, tell us why you think it's a good solution. 2) Format your code: stackoverflow.com/editing-help
    – cornuz
    Nov 21, 2014 at 11:16
  • Code-only answers are auto-flagged as low quality and as such are discouraged on stackoverflow. In the future please embellish your answer with details and explain why it is a solution to the question. This helps other users. Also - have you never heard of carriage returns?? Nov 21, 2014 at 11:47
-5

I tried to work out your question with a switch statement but I still required a for loop to parse the string . feel free to comment if I can improve the code

public class CharacterCount {
public static void main(String args[])
{
    String message="hello how are you";
    char[] array=message.toCharArray();
    int a=0;
    int b=0;
    int c=0;
    int d=0;
    int e=0;
    int f=0;
    int g=0;
    int h=0;
    int i=0;
    int space=0;
    int j=0;
    int k=0;
    int l=0;
    int m=0;
    int n=0;
    int o=0;
    int p=0;
    int q=0;
    int r=0;
    int s=0;
    int t=0;
    int u=0;
    int v=0;
    int w=0;
    int x=0;
    int y=0;
    int z=0;


    for(char element:array)
    {
        switch(element)
        {
        case 'a':
        a++;
        break;
        case 'b':
        b++;
        break;
        case 'c':c++;
        break;

        case 'd':d++;
        break;
        case 'e':e++;
        break;
        case 'f':f++;
        break;

        case 'g':g++;
        break;
        case 'h':
        h++;
        break;
        case 'i':i++;
        break;
        case 'j':j++;
        break;
        case 'k':k++;
        break;
        case 'l':l++;
        break;
        case 'm':m++;
        break;
        case 'n':m++;
        break;
        case 'o':o++;
        break;
        case 'p':p++;
        break;
        case 'q':q++;
        break;
        case 'r':r++;
        break;
        case 's':s++;
        break;
        case 't':t++;
        break;
        case 'u':u++;
        break;
        case 'v':v++;
        break;
        case 'w':w++;
        break;
        case 'x':x++;
        break;
        case 'y':y++;
        break;
        case 'z':z++;
        break;
        case ' ':space++;
        break;
        default :break;
        }
    }
    System.out.println("A "+a+" B "+ b +" C "+c+" D "+d+" E "+e+" F "+f+" G "+g+" H "+h);
    System.out.println("I "+i+" J "+j+" K "+k+" L "+l+" M "+m+" N "+n+" O "+o+" P "+p);
    System.out.println("Q "+q+" R "+r+" S "+s+" T "+t+" U "+u+" V "+v+" W "+w+" X "+x+" Y "+y+" Z "+z);
    System.out.println("SPACE "+space);
}

}

1
  • This is as far away from one-liner as possible. Terrible. Dec 9, 2015 at 19:36
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.