# Tutorial :How do I count the number of occurrences of a char in a String? ### 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).

### Solution:1

Try this method:

``StringTokenizer stOR = new StringTokenizer(someExpression, "||");  int orCount = stOR.countTokens()-1;  ``

### Solution:2

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

### Solution:3

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

### Solution:4

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

### Solution:5

``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?

### Solution:6

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>  ``

### Solution:7

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

### Solution:8

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

### Solution:9

``public static void getCharacter(String str){            int count[]= new int;            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]);          }          }  }  ``

### Solution:10

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

### Solution:11

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

}

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »