Find duplicate characters in String and count the number of events using Java

How to find the number of occurrences of a character in a string?

For example: A quick brown fox jumped over a lazy dog .

Below are some examples.

'a' = 1 'o' = 4 'space' = 8 '.' = 1 
+10
source share
29 answers
 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); } } 

Exit

 Enter the Statement:asdf23123sfsdf a 1 Times s 3 Times d 2 Times f 3 Times 
+7
source

You can use the following if 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); } } 

Please note that it will count all characters, not just letters.

+27
source
  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; } } 
+9
source

Java 8-way:

 "The quick brown fox jumped over the lazy dog." .chars() .mapToObj(i -> (char) i) .collect(Collectors.groupingBy(Object::toString, Collectors.counting())); 
+6
source

It would be best to create a Map to store your account. It will be Map<Character, Integer>

You need to iterate over each character of your string and check its alphabet. You can use the Character#isAlphabetic method to do this. If it's an alphabet , increase its number in Map . If the symbol is not already in the Map , then add it with a counter of 1 .

NOTE : - The 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} 
+5
source

This is an implementation without using any collection and with complexity of order n. Although the decision is good enough and doesn't use Collection, it doesn't seem to care about 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; } } 

Exit:

 ' ' 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 
+3
source

If your string contains only alphabets, you can use something 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."); } } } } 

Conclusion:

  'a' comes 2 times. 'b' comes 2 times. 'h' comes 3 times. 'l' comes 2 times. 
+3
source

Finding duplicates in String :

Example 1. Using a 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) ); } } 
+2
source

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

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 open class B {

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

}

+1
source

Using the Eclipse CharAdapter and CharBag :

 CharBag bag = CharAdapter.adapt("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

+1
source

You can also do it by iterating over String and using switch to check each individual character, adding a counter when it finds a match. Ah, maybe some code will become more clear:

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

Conclusion:

 A: 1 O: 4 Space: 8 Dot: 1 
+1
source

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

In java ... use 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
source
  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
source
 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
source
 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
source
  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
source
 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
source
 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
source
 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
source
 //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
source
 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
source
 public static void findDuplicate(String letter) { for(int i=0; i<letter.length();i++) { for( int j=i+1; j<letter.length();j++) { if(letter.charAt(i)==letter.charAt(j)) { System.out.println(letter.charAt(j)); break; } } } } 

findDuplicate ("Java");

OUTPUT: A

-2
source

All Articles