11
votes

How can I find the number of occurrences of a character in a string?

For example: The quick brown fox jumped over the lazy dog.

Some example outputs are below,

'a' = 1
'o' = 4
'space' = 8
'.' = 1
30
Is this a homework?Thinhbk

30 Answers

28
votes

You could use the following, provided String s is the string you want to process.

Map<Character,Integer> map = new HashMap<Character,Integer>();
for (int i = 0; i < s.length(); i++) {
  char c = s.charAt(i);
  if (map.containsKey(c)) {
    int cnt = map.get(c);
    map.put(c, ++cnt);
  } else {
    map.put(c, 1);
  }
}

Note, it will count all of the chars, not only letters.

12
votes

Java 8 way:

"The quick brown fox jumped over the lazy dog."
        .chars()
        .mapToObj(i -> (char) i)
        .collect(Collectors.groupingBy(Object::toString, Collectors.counting()));
10
votes
 void Findrepeter(){
    String s="mmababctamantlslmag";
    int distinct = 0 ;

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

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

            if(s.charAt(i)==s.charAt(j))
            {
                distinct++;

            }
        }   
        System.out.println(s.charAt(i)+"--"+distinct);
        String d=String.valueOf(s.charAt(i)).trim();
        s=s.replaceAll(d,"");
        distinct = 0;

    }

}
7
votes
import java.io.*;
public class CountChar 
{

    public static void main(String[] args) throws IOException
    {
      String ch;
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Enter the Statement:");
      ch=br.readLine();
      int count=0,len=0;
        do
        {  
          try
          {
          char name[]=ch.toCharArray();
              len=name.length;
              count=0;
              for(int j=0;j<len;j++)
               {
                  if((name[0]==name[j])&&((name[0]>=65&&name[0]<=91)||(name[0]>=97&&name[0]<=123))) 
                      count++;
               }
              if(count!=0)
                System.out.println(name[0]+" "+count+" Times");
              ch=ch.replace(""+name[0],"");          
          }
          catch(Exception ex){}
        }
        while(len!=1);
   }

}

Output

Enter the Statement:asdf23123sfsdf

a 1 Times

s 3 Times

d 2 Times

f 3 Times
6
votes

A better way would be to create a Map to store your count. That would be a Map<Character, Integer>

You need iterate over each character of your string, and check whether its an alphabet. You can use Character#isAlphabetic method for that. If it is an alphabet, increase its count in the Map. If the character is not already in the Map then add it with a count of 1.

NOTE: - Character.isAlphabetic method is new in Java 7. If you are using an older version, you should use Character#isLetter

    String str = "asdfasdfafk asd234asda";
    Map<Character, Integer> charMap = new HashMap<Character, Integer>();
    char[] arr = str.toCharArray();

    for (char value: arr) {

       if (Character.isAlphabetic(value)) {
           if (charMap.containsKey(value)) {
               charMap.put(value, charMap.get(value) + 1);

           } else {
               charMap.put(value, 1);
           }
       }
    }

    System.out.println(charMap);

OUTPUT: -

{f=3, d=4, s=4, a=6, k=1}
4
votes

If your string only contains alphabets then you can use some thing like this.

public class StringExample {
public static void main(String[] args) {
    String str = "abcdabghplhhnfl".toLowerCase();
    // create a integer array for 26 alphabets.
    // where index 0,1,2.. will be the container for frequency of a,b,c...
    Integer[] ar = new Integer[26];
    // fill the integer array with character frequency.
    for(int i=0;i<str.length();i++) {
        int j = str.charAt(i) -'a';
        if(ar[j]==null) {
            ar[j]= 1;
        }else {
            ar[j]+= 1;
        }
    }   
    // print only those alphabets having frequency greater then 1.
    for(int i=0;i<ar.length;i++) {
        if(ar[i]!=null && ar[i]>1) {
            char c = (char) (97+i);
            System.out.println("'"+c+"' comes "+ar[i]+" times.");
        }
    }
}
}

Output:

 'a' comes 2 times.
 'b' comes 2 times.
 'h' comes 3 times.
 'l' comes 2 times.
3
votes

Finding the duplicates in a String:

Example 1 : Using HashMap

public class a36 {
    public static void main(String[] args) {
        String a = "Gini Rani";
        fix(a);
    }//main
    public static void fix(String a ){
        Map<Character ,Integer> map = new HashMap<>();
        for (int i = 0; i <a.length() ; i++ ) {
        char ch = a.charAt(i);
                map.put(ch , map.getOrDefault(ch,0) +1 );
        }//for

       List<Character> list = new ArrayList<>();
       Set<Map.Entry<Character ,Integer> > entrySet = map.entrySet();

       for (  Map.Entry<Character ,Integer> entry : entrySet) {
             list.add( entry.getKey()  ); 

             System.out.printf(  " %s : %d %n" ,  entry.getKey(), entry.getValue()           );
       }//for
       System.out.println("Duplicate elements => " + list);

    }//fix
}

Example 2 : using Arrays.stream() in Java 8

public class a37 {
    public static void main(String[] args) {
        String aa = "Protijayi Gini";
        String[] stringarray = aa.split("");

    Map<String , Long> map =  Arrays.stream(stringarray)
        .collect(Collectors.groupingBy(c -> c , Collectors.counting()));
        map.forEach( (k, v) -> System.out.println(k + " : "+ v)        );
    }
}
3
votes

This is the implementation without using any Collection and with complexity order of n. Although the accepted solution is good enough and does not use Collection as well but it seems, it is not taking care of special characters.

import java.util.Arrays;

public class DuplicateCharactersInString {
    public static void main(String[] args) {
        String string = "check duplicate charcters in string";
        string = string.toLowerCase();
        char[] charAr = string.toCharArray();
        Arrays.sort(charAr);
        for (int i = 1; i < charAr.length;) {
            int count = recursiveMethod(charAr, i, 1);
            if (count > 1) {
                System.out.println("'" + charAr[i] + "' comes " + count + " times");
                i = i + count;
            } else
                i++;
        }
    }

    public static int recursiveMethod(char[] charAr, int i, int count) {
        if (ifEquals(charAr[i - 1], charAr[i])) {
            count = count + recursiveMethod(charAr, ++i, count);
        }
        return count;
    }

    public static boolean ifEquals(char a, char b) {
        return a == b;
    }
}

Output :

' ' comes 4 times
'a' comes 2 times
'c' comes 5 times
'e' comes 3 times
'h' comes 2 times
'i' comes 3 times
'n' comes 2 times
'r' comes 3 times
's' comes 2 times
't' comes 3 times
2
votes
public class dublicate 
{
public static void main(String...a)
{
    System.out.print("Enter the String");
    Scanner sc=new Scanner(System.in);
    String st=sc.nextLine();
    int [] ar=new int[256];
    for(int i=0;i<st.length();i++)
    {
        ar[st.charAt(i)]=ar[st.charAt(i)]+1;
    }
    for(int i=0;i<256;i++)
    {
        char ch=(char)i;
        if(ar[i]>0)
        {
            if(ar[i]==1)
            {
                System.out.print(ch);
            }
            else
            {
                System.out.print(ch+""+ar[i]);
            }
        }
    }

}
}
1
votes

Use google guava Multiset<String>.

Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(words);
for(Multiset.Entry<E> entry:wordsMultiset.entrySet()){
     System.out.println(entry.getElement()+" - "+entry.getCount());
}
1
votes
public static void main(String args[]) {
    char Char;
    int count;
    String a = "Hi my name is Rahul";
    a = a.toLowerCase();
    for (Char = 'a'; Char <= 'z'; Char++) {
        count = 0;
        for (int i = 0; i < a.length(); i++) {
            if (a.charAt(i) == Char) {
                count++;
            }
        }
        System.out.println("Number of occurences of " + Char + " is " + count);
    }
}
1
votes
public static void main(String[] args) {
        String name="AnuvratAnuvra";
        char[] arr = name.toCharArray();
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();

        for(char val:arr){          
            map.put(val,map.containsKey(val)?map.get(val)+1:1);         
        }

        for (Entry<Character, Integer> entry : map.entrySet()) {
            if(entry.getValue()>1){
            Character key = entry.getKey();
            Object value = entry.getValue();

            System.out.println(key + ":"+value);
            }
            }
    }
1
votes

class A {

public static void getDuplicates(String S) {
    int count = 0;
    String t = "";
    for (int i = 0; i < S.length() - 1; i++) {
        for (int j = i + 1; j < S.length(); j++) {
            if (S.charAt(i) == S.charAt(j) && !t.contains(S.charAt(j) + "")) {
                t = t + S.charAt(i);
            }
        }
    }
    System.out.println(t);
}

}

class B public class B {

public static void main(String[] args){
    A.getDuplicates("mymgsgkkabcdyy");

}

}

1
votes

You can also achieve it by iterating over your String and using a switch to check each individual character, adding a counter whenever it finds a match. Ah, maybe some code will make it clearer:

Main Application:

public static void main(String[] args) {

        String test = "The quick brown fox jumped over the lazy dog.";

        int countA = 0, countO = 0, countSpace = 0, countDot = 0;

        for (int i = 0; i < test.length(); i++) {
            switch (test.charAt(i)) {
                case 'a':
                case 'A': countA++; break;
                case 'o':
                case 'O': countO++; break;
                case ' ': countSpace++; break;
                case '.': countDot++; break;
            }
        }

        System.out.printf("%s%d%n%s%d%n%s%d%n%s%d", "A: ", countA, "O: ", countO, "Space: ", countSpace, "Dot: ", countDot);

    }

Output:

A: 1
O: 4
Space: 8
Dot: 1
1
votes
import java.util.HashMap;
import java.util.Scanner;


public class HashMapDemo {

    public static void main(String[] args) {
        //Create HashMap object to Store Element as Key and Value 
        HashMap<Character,Integer> hm= new HashMap<Character,Integer>();
        //Enter Your String From Console
        System.out.println("Enter an String:");
        //Create Scanner Class Object From Retrive the element from console to our java application
        Scanner sc = new Scanner(System.in);
        //Store Data in an string format
        String s1=sc.nextLine();
        //find the length of an string and check that hashmap object contain the character or not by using 
        //containskey() if that map object contain element only one than count that value as one or if it contain more than one than increment value 

        for(int i=0;i<s1.length();i++){
            if(!hm.containsKey(s1.charAt(i))){
                hm.put(s1.charAt(i),(Integer)1);
            }//if
            else{
                hm.put(s1.charAt(i),hm.get(s1.charAt(i))+1);
            }//else

        }//for

        System.out.println("The Charecters are:"+hm);
    }//main
}//HashMapDemo
1
votes

There are three ways to find duplicates

public class WAP_PrintDuplicates {

    public static void main(String[] args) {

        String input = "iabccdeffghhijkkkl";

        findDuplicate1(input);
        findDuplicate2(input);
        findDuplicate3(input);

    }

    private static void findDuplicate3(String input) {

        HashMap<Character, Integer> hm = new HashMap<Character, Integer>();

        for (int i = 0; i < input.length() - 1; i++) {
            int ch = input.charAt(i);
            if (hm.containsKey(input.charAt(i))) {
                int value = hm.get(input.charAt(i));
                hm.put(input.charAt(i), value + 1);
            } else {
                hm.put(input.charAt(i), 1);
            }
        }
        Set<Entry<Character, Integer>> entryObj = hm.entrySet();
        for (Entry<Character, Integer> entry : entryObj) {

            if (entry.getValue() > 1) {
                System.out.println("Duplicate: " + entry.getKey());
            }
        }

    }

    private static void findDuplicate2(String input) {

        int i = 0;

        for (int j = i + 1; j < input.length(); j++, i++) {

            if (input.charAt(i) == input.charAt(j)) {
                System.out.println("Duplicate is: " + input.charAt(i));
            }
        }

    }

    private static void findDuplicate1(String input) {
        // TODO Auto-generated method stub
        for (int i = 0; i < input.length(); i++) {

            for (int j = i + 1; j < input.length(); j++) {

                if (input.charAt(i) == input.charAt(j)) {
                    System.out.println("Duplicate is: " + input.charAt(i));
                }
            }
        }
    }
}
1
votes

Using Eclipse Collections CharAdapter and CharBag:

CharBag bag = 
    Strings.asChars("The quick brown fox jumped over the lazy dog.").toBag();

Assert.assertEquals(1, bag.occurrencesOf('a'));
Assert.assertEquals(4, bag.occurrencesOf('o'));
Assert.assertEquals(8, bag.occurrencesOf(' '));
Assert.assertEquals(1, bag.occurrencesOf('.'));

Note: I am a committer for Eclipse Collections

0
votes
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class DuplicateCountChar{

    public static void main(String[] args) {
        Scanner inputString = new Scanner(System.in);
        String token = inputString.nextLine();
        char[] ch = token.toCharArray();
        Map<Character, Integer> dupCountMap =  new HashMap<Character,Integer>();

        for (char c : ch) {
            if(dupCountMap.containsKey(c)) { 
                dupCountMap.put(c, dupCountMap.get(c)+1);
            }else {
                dupCountMap.put(c, 1);
            }
        }


        for (char c : ch) {
            System.out.println("Key = "+c+ "Value : "+dupCountMap.get(c));
        }

        Set<Character> keys = dupCountMap.keySet();
        for (Character character : keys) {
            System.out.println("Key = "+character+ " Value : " + dupCountMap.get(character));
        }

    }**
0
votes

In java... using for loop:

import java.util.Scanner;

/**
 *
 * @author MD SADDAM HUSSAIN */
public class Learn {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        String input = sc.next();
        char process[] = input.toCharArray();
        boolean status = false;
        int index = 0;
        for (int i = 0; i < process.length; i++) {
            for (int j = 0; j < process.length; j++) {

                if (i == j) {
                    continue;
                } else {
                    if (process[i] == process[j]) {
                        status = true;
                        index = i;
                        break;
                    } else {
                        status = false;

                    }
                }

            }
            if (status) {
                System.out.print("" + process[index]);

            }
        }
    }
}
0
votes
  public class StringCountwithOutHashMap {
  public static void main(String[] args) {
    System.out.println("Plz Enter Your String: ");
    Scanner sc = new Scanner(System.in);
    String s1 = sc.nextLine();
    int count = 0;
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j < s1.length(); j++) {
            if (s1.charAt(i) == s1.charAt(j)) {
                count++;
            } 
        } 
        System.out.println(s1.charAt(i) + " --> " + count);
        String d = String.valueOf(s1.charAt(i)).trim();
        s1 = s1.replaceAll(d, "");
        count = 0;
    }}}
0
votes
public class CountH {

    public static void main(String[] args) {
        String input = "Hi how are you";

        char charCount = 'h';
        int count = 0;

        input = input.toLowerCase();

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

            if (input.charAt(i) == charCount) {
                count++;
            }

        }

        System.out.println(count);
    }
}
0
votes
public class DuplicateValue {

    public static void main(String[] args) {

        String s = "hezzz";

        char []st=s.toCharArray();

        int count=0;

        Set<Character> ch=new HashSet<>();
        for(Character cg:st){
            if(ch.add(cg)==false){
                int occurrences = Collections.frequency(ch, cg);
                count+=occurrences;
                if(count>1){
                System.out.println(cg + ": This character exist more than one time");
                }
                else{
                System.out.println(cg);
                }
            }
        }

        System.out.println(count);
    }
}
0
votes
                       Map<Character,Integer> listMap = new HashMap<Character,Integer>();                         
                       Scanner in= new Scanner(System.in);
                       System.out.println("enter the string");
                       String name=in.nextLine().toString();
                       Integer value=0;
                       for(int i=0;i<name.length();i++){

                                     if(i==0){
                                                   listMap.put(name.charAt(0), 1);
                                     }
                                     else if(listMap.containsKey(name.charAt(i))){
                                                                value=listMap.get(name.charAt(i));
                                                                listMap.put(name.charAt(i), value+1);

                                     }else listMap.put(name.charAt(i),1);


                       }

                       System.out.println(listMap);
0
votes
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String reverse1;
        String reverse2;
        int count = 0;
        while(n > 0)
        {
            String A = sc.next();
            String B = sc.next();
            reverse1 = new StringBuffer(A).reverse().toString();
            reverse2 = new StringBuffer(B).reverse().toString();
            if(!A.equals(reverse1))
            {
                for(int i = 0; i < A.length(); i++)
                {
                    for(int j = 0; j < A.length(); j++)
                    {
                        if(A.charAt(j) == A.charAt(i))
                        {
                            count++;
                        }
                    }
                    if(count % 2 != 0)
                    {
                        A.replace(A.charAt(i),"");
                        count = 0;
                    }
                }
                System.out.println(A);
            }
            n--;
        } 
    }
}
0
votes
public class list {

    public static String name(Character k){
        String s="the quick brown fox jumped over the lazy dog.";
        int count=0;
        String l1="";
        String l="";
        List<Character> list=new ArrayList<Character>();
        for(int i1=0;i1<s.length();i1++){
            list.add(s.charAt(i1));
        }
        list.sort(null);
        for (Character character : list) {
            l+=character;
        }
        for (int i1=0;i1<l.length();i1++) {
            if((l.charAt(i1)==k)){
                count+=1;
                l1=l.charAt(i1)+" "+Integer.toString(count);
                if(k==' '){
                    l1="Space"+" "+Integer.toString(count);
                }
            }else{
                count=0;
            }
        }
        return l1;
    }
    public static void main(String[] args){
        String g = name('.');
        System.out.println(g);
    }
}
0
votes

Simple and Easy way to find char occurrences >

void findOccurrences() {
    String s = "The quick brown fox jumped over the lazy dog.";
    Map<String, Integer> occurrences = new LinkedHashMap<String, Integer>();
    
    for (String ch : s.split("")) {
        Integer count = occurrences.get(ch);
        occurrences.put(ch, count == null ? 1 : count + 1);
    }
    System.out.println(occurrences);
}

This will print output as:

{T=1, h=2, e=4, =8, q=1, u=2, i=1, c=1, k=1, b=1, r=2, o=4, w=1, n=1, f=1, x=1, j=1, m=1, p=1, d=2, v=1, t=1, l=1, a=1, z=1, y=1, g=1, .=1}

-1
votes
public static void main(String[] args) {
        char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
        char[][] countArr = new char[array.length][2];
        int lastIndex = 0;
        for (char c : array) {
            int foundIndex = -1;
            for (int i = 0; i < lastIndex; i++) {
                if (countArr[i][0] == c) {
                    foundIndex = i;
                    break;
                }
            }
            if (foundIndex >= 0) {
                int a = countArr[foundIndex][1];
                countArr[foundIndex][1] = (char) ++a;
            } else {
                countArr[lastIndex][0] = c;
                countArr[lastIndex][1] = '1';
                lastIndex++;
            }
        }
        for (int i = 0; i < lastIndex; i++) {
            System.out.println(countArr[i][0] + " " + countArr[i][1]);
        }
    }
-1
votes
//sample Input
/*2
7
saska
toro
winn
toro
vanco
saska
toro
3
edddddd
edddddd
edddddd*/
//sample output
/*4
  1*/

import java.util.ArrayList;
import java.util.Scanner;

public class MyTestWhere {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int count, line;
        Scanner sn = new Scanner(System.in);
        count = sn.nextInt();
        sn.nextLine();          
        for (int i = 0; i < count; i++) { 
            line = sn.nextInt();
            sn.nextLine();
        //  String numArr[] = new String[line];
            ArrayList<String> Arr=new ArrayList<String>();
            String first = sn.nextLine();
            Arr.add(first);String f;
            for (int j = 1; j < line; j++) {
                f= sn.nextLine();
                for(int k=0;k<Arr.size();k++){
                    if(f.equalsIgnoreCase(Arr.get(k)))break;
                    else if(k== (Arr.size()-1)){Arr.add(f);}

                }
            }   

            System.out.println(Arr.size());

        }
    }
}
-1
votes
import java.util.Scanner;

    class Test
    { 

        static String s2="";
        int l;
        void countDuplicateCharacters(String Str)
        {
            String S=Str.toLowerCase();
            for(int i=0;i<S.length();i++)
            {
                int k=1;
                boolean value=  repeatedCheck(S.charAt(i));
                if(value==true)
                    continue;
                for(int j=i+1;j<S.length();j++)
                {


                    if(S.charAt(i)==S.charAt(j))
                    {   k++;

                    }

            }
                System.out.println("character  '" +S.charAt(i)+"' : "+k);

                s2=s2+S.charAt(i);
            }

        }

        boolean repeatedCheck(char ch)
        {
            l=s2.length();
            for (int i=0;i<l;i++)
            {
                if(s2.charAt(i)==ch)
                {
                    return true;
                }
            }

            return false;
        }

    }

    public class Duplicacy {

        public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("Enter any String");
            String s=sc.nextLine();
            Test t=new Test();
            t.countDuplicateCharacters(s);


        }}
-1
votes

I solved this with 2 dimensional array. Input: aaaabbbcdefggggh Output:a4b3cdefg4h

int[][] arr = new int[10][2];
    String st = "aaaabbbcdefggggh";
    char[] stArr = st.toCharArray();
    int i = 0;
    int j = 0;
    for (int k = 0; k < stArr.length; k++) {
        if (k == 0) {
            arr[i][j] = stArr[k];
            arr[i][j + 1] = 1;
        } else {
            if (arr[i][j] == stArr[k]) {
                arr[i][j + 1] = arr[i][j + 1] + 1;
            } else {
                arr[++i][j] = stArr[k];
                arr[i][j + 1] = 1;
            }
        }
    }
    System.out.print(arr.length);
    String output = "";
    for (int m = 0; m < arr.length; m++) {
        if (arr[m][1] > 0) {
            String character = Character.toString((char) arr[m][0]);
            String cnt = arr[m][1] > 1 ? String.valueOf(arr[m][1]) : "";
            output = output + character + cnt;

        }
    }
    System.out.print(output);