Today's programming exercise is to write a program to find repeated characters in a String. For example, if given input to your program is "Java", it should print all duplicates characters, i.e. characters appear more than once in String and their count e.g. a = 2 because character 'a' has appeared twice in String "Java". This is also a very popular coding question on the various level of Java interviews and written test, where you need to write code. On difficulty level, this question is at par with prime numbers or Fibonacci series. I personally like this exercise because it gives beginners an opportunity to familiar with the concept of Map data structure, which allows you store mappings in the form of key and value. Since Map is heavily used in any enterprise Java application, good knowledge of this data structure is highly desirable among any level of Java programmers.
By the way, there are a couple of variants of this problem, which you may want to look before going for an interview. Sometimes an interviewer will ask you to read a file and print all duplicate characters and their count, core logic will remain same, all you need to do is demonstrate how much you know about File IO in Java e.g. streaming file if it's very large rather than reading the whole file in memory.
If you look at below example, there is only one static method called printDuplicateCharacters(), which does both this job. We first got the character array from String by calling toCharArray().
Next we are using HashMap to store characters and their count. We use containsKey() method to check if key, which is a character already exists or not, if already exists we get the old count from HashMap by calling get() method and store it back after incrementing it by 1.
Once we build our Map with each character and count, next task is to loop through Map and check each entry, if count, which is the value of Entry is greater than 1, then that character has occurred more than once. You can now print duplicate characters or do whatever you want with them.
That's all on how to find duplicate characters in a String. Next time if this question is asked to you in a programming job interview, you can confidently write a solution and can explain them. Remember this question is also asked as write a Java program to find repeated characters of a given String, so don't get confused yourself in wording, the algorithm will remain same.
By the way, there are a couple of variants of this problem, which you may want to look before going for an interview. Sometimes an interviewer will ask you to read a file and print all duplicate characters and their count, core logic will remain same, all you need to do is demonstrate how much you know about File IO in Java e.g. streaming file if it's very large rather than reading the whole file in memory.
Java Program to find Repeated Characters of String
The standard way to solve this problem is to get the character array from String, iterate through that and build a Map with character and their count. Then iterate through that Map and print characters which have appeared more than once. So you actually need two loops to do the job, the first loop to build the map and second loop to print characters and counts.If you look at below example, there is only one static method called printDuplicateCharacters(), which does both this job. We first got the character array from String by calling toCharArray().
Next we are using HashMap to store characters and their count. We use containsKey() method to check if key, which is a character already exists or not, if already exists we get the old count from HashMap by calling get() method and store it back after incrementing it by 1.
Once we build our Map with each character and count, next task is to loop through Map and check each entry, if count, which is the value of Entry is greater than 1, then that character has occurred more than once. You can now print duplicate characters or do whatever you want with them.import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; /** * Java Program to find duplicate characters in String. * * * @author http://java67.blogspot.com */ public class FindDuplicateCharacters{ public static void main(String args[]) { printDuplicateCharacters("Programming"); printDuplicateCharacters("Combination"); printDuplicateCharacters("Java"); } /* * Find all duplicate characters in a String and print each of them. */ public static void printDuplicateCharacters(String word) { char[] characters = word.toCharArray(); // build HashMap with character and number of times they appear in String Map<Character, Integer> charMap = new HashMap<Character, Integer>(); for (Character ch : characters) { if (charMap.containsKey(ch)) { charMap.put(ch, charMap.get(ch) + 1); } else { charMap.put(ch, 1); } } // Iterate through HashMap to print all duplicate characters of String Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet(); System.out.printf("List of duplicate characters in String '%s' %n", word); for (Map.Entry<Character, Integer> entry : entrySet) { if (entry.getValue() > 1) { System.out.printf("%s : %d %n", entry.getKey(), entry.getValue()); } } } } Output List of duplicate characters in String 'Programming' g : 2 r : 2 m : 2 List of duplicate characters in String 'Combination' n : 2 o : 2 i : 2 List of duplicate characters in String 'Java'
That's all on how to find duplicate characters in a String. Next time if this question is asked to you in a programming job interview, you can confidently write a solution and can explain them. Remember this question is also asked as write a Java program to find repeated characters of a given String, so don't get confused yourself in wording, the algorithm will remain same.
How do you do it without using any additional data structure.
ReplyDeleteimport java.io.*;
Deletepublic class Str
{
public static void main(String arg[])throws Exception
{
String res="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String a=br.readLine();
while(a.length()>0)
{
int c=0;
for(int j=0;j<a.length();j++)
{
if(a.charAt(0)==a.charAt(j))
c=c+1;
}
res=res+a.charAt(0)+"="+c+"\n";
String k[]=a.split(a.charAt(0)+"");
a=new String("");
for(int i=0;i<k.length;i++)
a=a+k[i];
}
System.out.println(res);
}
}
Thanks its very useful to me..
DeleteGood solution, but you can see without using data structure time complexity of your solution grows from O(n) to O(n^2). This is actually good learning point, choice of good data structure improves your algorithm.
DeleteThanks "Anonymous", very helpful stuff for searching with minimal resources.
Deletepackage StringPac;
Deleteimport java.util.Scanner;
/**
* @author Tarique
* How to Print duplicate characters from String?
*/
public class duplicateChar {
/**
* @param args
*/
public static void main(String[] args)
{
//String str = "Nitin";
Scanner sc = new Scanner(System.in);
String str = sc.next();
char d = 0;
int count = 0;
/* for(int i=0;i<str.length();i++)
{
char c = str.charAt(i);
System.out.println(c);
}*/
for (int i = 0; i < str.length(); i++)
{
for (int j = i+1; j < str.length(); j++)
{
if (str.charAt(i)==str.charAt(j))
{
if(d!=str.charAt(i))
{
count++;
d = str.charAt(i);
System.out.println("Duplicate Charaacter is "+d);
break;
}
}
}
}
System.out.println("Number of duplicate character is "+count);
}
}
Why is the 'a' of Java not occuring twice?
ReplyDelete@Anonymous, It actually does print 'a' twice for 'Java', its just that I missed when I copied output from Eclipse. You can try running program in your machine, it will print.
DeleteList of duplicate characters in String 'Java'
a : 2
How to add two arrays A={3,5,2,1} and B={6,8,9,2,4} index by index into third array C={4,5,8,9,6} answer this please..
ReplyDelete@Vekatesh, if all array of same length, you can use a for loop to do this job. Just iterate over both array, take each element from same index, add them and store into third array.
Delete
Delete///please refer below code to copy one arrays into other ,many approaches is for this but i have implemented only two
package com.java8.demo;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
public class MergeArrays {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a[]={"a","b","c","r","g","f"};
String b[]={"d","e"};
//method 1
Object[] combined = ArrayUtils.addAll(a, b);
System.out.println("combined arrays are:"+Arrays.toString(combined));
//method 2
List ls=new ArrayList<>(Arrays.asList(a));
ls.addAll(Arrays.asList(b));
Object o[]=ls.toArray();
System.out.println("Merged arrays Is:"+Arrays.toString(o));
//for sorting the arrays
Arrays.sort(o);
System.out.println("sort the merged ayyars:"+Arrays.toString(o));
int d=Arrays.binarySearch(o, "b");
System.out.println("Searched Key's index is:"+Arrays.binarySearch(o, "k")+d);
}
}
You can also find using a single loop.
ReplyDeletepublic static boolean checkRepeatingCharactersFromMap(String s1) {
boolean repeat = false;
if (s1 != null && s1.length() > 0) {
char[] s1Array = s1.toCharArray();
Set set = new TreeSet();
Set repeatChar = new TreeSet();
for (char c1: s1Array) {
if (!set.add(c1)) {
// System.out.print(c1 + " "); //if you want to print each occurance of the repeating character
repeatChar.add(c1);
repeat = true;
// return true; //end the loop if you don't want to cache the repeating characters
}
}
System.out.print(repeatChar);
}
return repeat;
}
@Genius, it will work but it will not print duplicates in the order they appear in original String. Nevertheless, if that's not stated, you can use it. Replacing TreeMap with LinkedHashMap will print the repeated character in the same order they appear in given input.
DeleteString s = "javaqjjcxcdf";
ReplyDeletechar[] charArray = s.toCharArray();
Map map = new HashMap();
/*for (Character character : charArray) {
if (map.containsKey(character)) {
map.put(character, map.get(character) + 1);
} else {
map.put(character, 1);
}
}*/
for (Character character : charArray) {
map.put(character, map.get(character) != null?map.get(character)+1:1);
}
System.out.println(map);
@Vikas, good choice of using ternary operator, much cleaner.
DeleteJust one changed need as the type of map should like Map map = new HashMap();
DeleteAll good, good to see example with one loop itself.
Python code:
ReplyDeleteduplicate=[]
first_time=[]
a = ""Hello world"
for i in a:
if i not in first_time:
first_time.append(i)
else:
duplicate.append(i)
print "".join(duplicate)
@Anonymous, Thanks for providing Python solution, neat.
Deletel1=list('Java')
ReplyDeletel2=set(l1)
[l1.remove(x) for x in l2]
print l1
Hello @Anonymous, Nice solution, is it Groovy, Scala or Ruby?
Delete@Javin: How about my solution?
ReplyDeleteMy solution even prints in alphabetical order. Very much memory efficient. If the question is only to find those characters which occur more than once, then my solution runs perfectly fine.
import java.util.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int len = s.length();
int[] charCount = new int[26];
for(int i = 0; i=65 && c<=90)
c=(char)(c+32);
if(c>=97 && c<=122)
charCount[c-97]+=1;
}
for(int i = 0; i<26; i++){
if(charCount[i]>1)
System.out.println((char)(i+97) + " : " + charCount[i]);
}
}
}
what is variable c ? atleast put the code without compilation errors
Deletepackage Strings;
ReplyDeleteimport java.util.ArrayList;
import java.util.List;
public class PrintDuplicateStrings {
public static void main(String[] args) {
String s = "hello world";
char[] chars = s.toCharArray();
int i,j = 0;
List finalList = new ArrayList();
for(i=0;i<chars.length;i++){
for(j=i+1;j<chars.length;j++){
if(!finalList.contains(String.valueOf(chars[i])) && chars[i]==chars[j]){
finalList.add(String.valueOf(chars[i]));
}
}
}
System.out.println("-- "+finalList);
}
}
You can avoid inner loop by adding a one more condition before inner loop, that avoids inner loop if a repeated character occurs.
Deletepublic static void printDuplicateCharsInString(String str) {
if(str==null && str.length() <=0 ) {
return;
}
int length= str.length();
List list= new ArrayList<>();
char ch;
int counter;
for(int i=0; i<length ;i++ ) {
ch=str.toLowerCase().charAt(i);
counter=1;
if( !list.contains(ch) && ch !=' ') {
for(int j=i+1;j<length; j++) {
if(ch== str.charAt(j)) {
list.add(ch);
counter++;
//break;
}
}
System.out.println("Character: '"+ch +"' occurs "+counter+" times");
}
}
System.out.println("Duplicate Chars: "+list.toString());
}
//Program to print duplicate characters in string
ReplyDelete/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
static boolean find(char[] update,char ch){
for(int i=0;i<update.length;i++)
if(update[i]==ch)
return false;
return true;
}
static void solution(String str){
char[] ar=str.toCharArray();
char[] update=new char[ar.length];
int i=0,z=0;
while(i<ar.length-1){
int j=i+1;
while(j<ar.length){
if(find(update,ar[j])&&ar[i]==ar[j]){
update[z++]=ar[i];
System.out.print(ar[i]+" ");
break;
}
j++;
}
i++;
}
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner scan=new Scanner(System.in);
String str=scan.nextLine();
solution(str);
}
}
i am getting null pointer exception how to solve it
ReplyDeleteI need to know how you print a character occurrence count Eg: Strins s = "1111223331123444" so o/p should be 14223312213143
ReplyDeletepackage Arrys;
ReplyDeleteimport java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
public class TwoStringPrograme {
public static void main(String[] args) {
String a="aaaxbbcccbaaasss";
char ch;
List cha=new ArrayList();
int count1;
char a1[]=a.toCharArray();
for(int i=0;i<a1.length;i++)
{
count1=0;
ch=a.charAt(i);
if(!cha.contains(ch))
{
for(int j=0;j<a1.length;j++)
{
if(ch==a1[j])
{
count1++;
}
}
System.out.println(ch+"--"+count1);
cha.add(ch);
}
}
} }
// without using any buildin function
ReplyDeletepublic 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]);
}
}
public void printDups(String str) {
ReplyDeleteif(str != null && str.length() > 0) {
char [] dupArr = str.toCharArray();
System.out.println("Dup Array ");
String dups ="";
for(int i=0; ii; j--){
if (dupArr[i] == dupArr[j]) {
dups = (dups+dupArr[i]).trim();
System.out.print(dupArr[i]);
}
}
}
}
}
Instead of clumsy solutions above, just loop the string once from left to right so to speak and at every character check if it also exists on the right hand side yet left to loop. A one liner and much easier to read. Work smarter, not harder!
ReplyDelete#python Code
ReplyDeleteimport sys
myStr='java'
#try with javaav
first_time=[]
duplicate=[]
#Empty String
if len(myStr)<1:
print "empty string"
sys.exit()
#iterating over the string
for i in myStr:
if i not in first_time:
first_time.append(i)
else:
if i not in duplicate:
duplicate.append(i)
print "".join(duplicate)
output: a
output 2nd test case: av
Credits- above anonymous coder
class Practise3
ReplyDelete{
public static void main(String[] args) throws ArrayIndexOutOfBoundsException
{
for(int i=0;i<args.length;i++)
{
System.out.println("Enter the string :" + args[i]);
String s = (String)args[i];
System.out.println(s);
try
{
for( int k =0; k<s.length();k++)
{
for(int j = k+1; j!=s.length();j++)
{
char var = s.charAt(k);
if(var == s.charAt(j))
{
System.out.println("duplicate character is : " + s.charAt(j));
}
else
{
System.out.println(" no duplicates found" + ".." + s.charAt(k));
}
}
}
}
catch (Exception e)
{
System.out.println("no");
}
}
}
}
I just tried using String class and its methods
Why not recursion? It's powerful and logical.
ReplyDeletepublic class StringDuplicate {
//search from the beginning of the string
public static void printDupes(String string) {
//specify exit case, when we finish the whole string
if(string.length() == 0) return;
//find the string in which the character you're searching for is dropped
String substring = string.substring(1);
//if we found that character on the substring, we sysout that b**ch
if(substring.indexOf(string.charAt(0)) > 0) {
System.out.println(string.charAt(0));
}
//we let the recursion go to the shorter string...
//by the process of induction, this will always terminate ;)
printDupes(substring);
}
public static void main(String[] args) {
printDupes(args[0]);
}
}
Why not recursion? Less storage, sleek, unique, and cool! :)
ReplyDeletepublic class StringDuplicate {
public static void printDupes(String string) {
//exit condition
if(string.length() == 0) return;
//find the substring in which to see if the first character is in
String substring = string.substring(1);
//what you do if you find it? print it!
if(substring.indexOf(string.charAt(0)) > 0) {
System.out.println(string.charAt(0));
}
//recusion on that b*tch
printDupes(substring);
}
public static void main(String args[]) {
printDupes(args[0]); //utilize command line arguments for general cases
}
}
@artsArt, yes, you can use recursion, no problem with that, but your solution will only print the duplicate characters, not their count. How can you improve the solution to print the count of duplicate character?
Deletechecks for words separated by space, removers symbols too.
ReplyDeletedef removechar(dup):
symbol = "~`!@#$%^&*()_-+={}[]:>;',</?*-+"
for i in dup:
if i in symbol or i is ' ':
dup.remove(i)
return dup
def duplicate(str):
l = []
dup = []
str = list(str)
for i in str:
try:
j = list(i)
for k in j:
if k not in l:
l.append(k)
else:
dup.append(k)
except:
print "No Duplicate"
if len(dup) == '0':
print "No Dupliates"
else:
d = []
final = dup
for i in dup:
if i not in d:
d.append(i)
print "Total numbe of duplicates:",len(removechar(d)),"\nThey are:",','.join(removechar(d))
if __name__ == '__main__':
duplicate(raw_input("Enter the string"))
public static void printDuplicatechar(String s) {
ReplyDeletechar[] arr = s.toCharArray();
List list=new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
int h = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j]) {
h++;
if (h >= 2) {
list.add(arr[i]);
}
}
}
}
list.stream().distinct().forEach(e->System.out.println(e));
}
Map map = Arrays.stream(s.split("")).collect(Collectors.groupingBy(c -> c , Collectors.counting()));
ReplyDeleteList duplicates = map.entrySet().stream().filter(entry -> entry.getValue() > 1).map(k -> k.getKey()).collect(Collectors.toList());
package logic;
ReplyDeletepublic class DuplicateChar {
public static void findDuplicateCharacters(String input1)
{
int i;
char[] a=input1.toCharArray();
int h[]=new int[26];
for(i=0;i64&&a[i]<95)
{
h[a[i]-65]++;
}
if(a[i]>95&&a[i]<123)
{
h[a[i]-97]++;
}
}
for(i=0;i64&&a[i]<95)
{
if(h[a[i]-65]>1)
System.out.println(a[i]+" "+h[a[i]-65]);
h[a[i]-65]=0;
}
if(a[i]>95&&a[i]<123)
{
if(h[a[i]-97]>1)
System.out.println(a[i]+" "+h[a[i]-97]);
h[a[i]-97]=0;
}
}
}
public static void main(String args[])
{
findDuplicateCharacters("programming");
}
}
public class Duplicatechar {
ReplyDeletepublic static void main(String[] args) {
String s ="java";
char x;
int i;
int c=0;
String str2=s.substring(1);
for(i=0;i<s.length();i++)
{
c=0;
x=s.charAt(i);
for(int j=0;j<str2.length();j++)
{
char y=str2.charAt(j);
if(x==y)
{
c++;
if(c==2)
System.out.println("the duplicate char "+x);
}
}
}
}
}
I have one mistake it print for me twice the comment that the duplicate character is a .. can anyone help me .. thanks
public class RemoveDup
ReplyDelete{
public static void main(String args[])
{
String s;
int i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter any String");
s=sc.next();
char[] chars= s.toCharArray();
Set charSet = new LinkedHashSet();
for (char c : chars)
{
charSet.add(c);
}
StringBuilder sb = new StringBuilder();//to buffer characters
for (Character character : charSet)
{
sb.append(character);
}
System.out.println(sb.toString());
}
}
#include
ReplyDelete#include
void main()
{
char s[100],ch;
int i,j,n,flag=0;
printf("Enter\n");
scanf_s("%s",s,8);
n=strlen(s);
printf("%d\n", n);
for(i=0;i=2)
{
printf("%c\n", ch);
}
else
{
printf("No\n");
}
}
#include
ReplyDelete#include
#include
using namespace std;
struct node
{
char ch;
int count;
struct node *next;
};
void main ()
{
node * Head = NULL;
node * crawl = Head;
char input[100];
memset(input,0,100);
printf("Enter the string :- \n");
scanf("%[^\n]s",&input);
if(input == NULL)
{
printf("NULL String!!!");
getch();
return;
}
int nLen = strlen(input);
if(nLen <= 1)
{
printf("Invalid String!!!");
getch();
return;
}
for(int n = 0; n 0)
{
if(Head == NULL)
{
Head = new node();
Head->next = NULL;
Head->ch = ref;
Head->count = nCount;
}
else
{
crawl = Head;
while (crawl->next != NULL && crawl->ch != ref)
{
crawl= crawl->next;
}
if(crawl->next == NULL)
{
if(crawl->ch != ref)
{
crawl->next = new node();
crawl = crawl->next;
crawl->next = NULL;
crawl->ch = ref;
crawl->count = nCount;
}
}
}
}
}
while(Head != NULL)
{
printf("%c is duplicated %d times\n",Head->ch,Head->count);
crawl = Head;
Head = Head->next;
delete crawl;
}
}
#include
ReplyDelete#include
#include
using namespace std;
struct node
{
char ch;
int count;
struct node *next;
};
void main ()
{
node * Head = NULL;
node * crawl = Head;
char input[100];
memset(input,0,100);
printf("Enter the string :- \n");
scanf("%[^\n]s",&input);
if(input == NULL)
{
printf("NULL String!!!");
getch();
return;
}
int nLen = strlen(input);
if(nLen <= 1)
{
printf("Invalid String!!!");
getch();
return;
}
for(int n = 0; n 0)
{
if(Head == NULL)
{
Head = new node();
Head->next = NULL;
Head->ch = ref;
Head->count = nCount;
}
else
{
crawl = Head;
while (crawl->next != NULL && crawl->ch != ref)
{
crawl= crawl->next;
}
if(crawl->next == NULL)
{
if(crawl->ch != ref)
{
crawl->next = new node();
crawl = crawl->next;
crawl->next = NULL;
crawl->ch = ref;
crawl->count = nCount;
}
}
}
}
}
while(Head != NULL)
{
printf("%c is duplicated %d times\n",Head->ch,Head->count);
crawl = Head;
Head = Head->next;
delete crawl;
}
}
See following solution with O(n) complexity.
ReplyDeletepublic static void FindDuplicateCharacters(String str){
if(str == null || str.length() == 0){
System.out.println("Invalid String");
return;
}
int[] counter = new int[128];
for(char c : str.toCharArray()){
counter[c]++;
}
for(int i = 0 ; i < str.length(); i++){
char c = str.charAt(i);
if(counter[c] > 1){
System.out.println(c);
counter[c] = 1;
}
}
}
a=raw_input("Enter The String")
ReplyDeleteprint set([x for x in a if a.count(x)>1])
In Python
System.out.println("Please Enter Your String");
ReplyDeleteScanner sc = new Scanner(System.in);
String inputString = sc.next();
System.out.println("Your String ::: " + inputString);
if(null != inputString && inputString.length() > 0) {
for(int i = 0; i < inputString.length(); i++) {
int j = i;
while(j > 0) {
if(inputString.charAt(i) == inputString.charAt(j-1) )
System.out.println(inputString.charAt(i));
j--;
}
}
}
sc.close();
I will use map.put(c[i], map.getOrDefault(c[i], 1) + 1);
ReplyDeleteto avoid else condition
Hello Nitesh, that is good but how about getOrDefault() method, do you know from which Java version it is available?
Deletei'm beginner so my solution maybe is not rational. I tried it in c++
ReplyDelete#include
#include
using namespace std;
void main()
{
char s[20], *p, s_[2]="", s1[20]="";
cin >> s;
p=s;
while (strlen(p)>0)
{
strncpy_s(s_, p, 1);
strncpy_s(s1, s, strlen(s)-strlen(p));
if(strrchr(p, *p)!=strchr(p, *p)
&& strchr((p+strcspn(p, s_)+1), *p)==strrchr(p, *p)
&& strcspn(s1, s_)==strlen(s1) )
cout << *p << ": " << 2 << endl;
p++;
}
system("pause");
}
import java.util.Scanner;
ReplyDeletepublic class DuplicateString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] str = sc.next().toLowerCase().toCharArray();
int[] charArray = new int[26];
for (int i = 0; i < str.length; i++) {
charArray[Math.abs(97-str[i])]++;
}
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] > 1) {
System.out.printf("%c",Math.abs(97+i));
System.out.println();
}
}
}
}
#include
ReplyDelete2
#include
3
#include
4
#include
5
6
int main() {
7
char a[10];
8
int i,j,has[1000]={0},l;
9
scanf("%s",a);
10
l=strlen(a);
11
for(i=0;i1)
17
{
18
printf("%c -> %d\n",i+65,has[i]);
19
}
20
}
21
22
}
23
private static void characterCount(String str) {
ReplyDeleteHashMap charCountMap = new HashMap<>();
for (Character ch : str.toLowerCase().toString().toCharArray()) {
Integer count = charCountMap.putIfAbsent(ch, 1);
if (null != count) {
charCountMap.put(ch, charCountMap.get(ch) + 1);
}
}
Map charMap =
charCountMap.entrySet().stream().filter(map -> map.getValue() != 1).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
System.out.println(charMap);
}
public class RemoveDuplicatesFromString {
ReplyDeletepublic static void main(String[] args) {
String input = "hello world";
String output = removeDuplicates(input);
System.out.println(output);
}
private static String removeDuplicates(String input) {
HashSet mySet = new HashSet();
String output="";
for(Character c :input.trim().replaceAll(" ", "").toCharArray())
{
if(mySet.add(c)==false)
if(!output.contains(c+""))
output = output+c;
}
return output;
}
}