how to check duplicate characters in string in java code example

Example 1: counting repeated characters in a string in java

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;

    }

}

Example 2: how to remove duplicate elements from char array in java

public static void main(String[] args) {
    Main main = new Main();
    char[] array = {'e','a','b','a','c','d','b','d','c','e'};
    main.getCharArray(array);
}

private char[] getCharArray(char[] array) {
    String _array = "";
    for(int i = 0; i < array.length; i++) {
        if(_array.indexOf(array[i]) == -1) // check if a char already exist, if not exist then return -1
            _array = _array+array[i];      // add new char
    }
    return _array.toCharArray();
}

Example 3: counting repeated characters in a string in java

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

}

Tags:

Misc Example