Print only duplicate character in string - Python & Java
using lambda in java
public class etst {
public static void main(String[] args) {
String text = "ramanrayat";
HashMap<Character,Integer> hm = new HashMap<>();
for(Character c: text.toCharArray()){
if(!hm.containsKey(c)){
hm.put(c,1);
}else{
hm.put(c,hm.get(c)+1);
}
}
hm.forEach((a,b)-> {if(b>1) System.out.println(a+""+b);});
}
}
Java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class test123 {
public static void main(String[] args) {
String text = "raman rayat";
HashMap<Character, Integer> hm = new HashMap<>();
for(int i = 0;i<text.length();i++){
if(!hm.containsKey(text.charAt(i)))
{
if((text.charAt(i)!=' ')){
hm.put(text.charAt(i),1);
}
}else{
hm.put(text.charAt(i),hm.get(text.charAt(i))+1);
}
}
for(Map.Entry<Character,Integer> item: hm.entrySet()){
char key =item.getKey();
int value = item.getValue();
if(value>1){
System.out.println(key+","+value);
}
}
import java.util.Iterator;
import java.util.Map;
public class test123 {
public static void main(String[] args) {
String text = "raman rayat";
HashMap<Character, Integer> hm = new HashMap<>();
for(int i = 0;i<text.length();i++){
if(!hm.containsKey(text.charAt(i)))
{
if((text.charAt(i)!=' ')){
hm.put(text.charAt(i),1);
}
}else{
hm.put(text.charAt(i),hm.get(text.charAt(i))+1);
}
}
for(Map.Entry<Character,Integer> item: hm.entrySet()){
char key =item.getKey();
int value = item.getValue();
if(value>1){
System.out.println(key+","+value);
}
}
Python
a = "ramanrayat"
d = {}
for i in range(len(a)):
if(a[i] not in d):
d[a[i]]=1
else:
d[a[i]]=d[a[i]]+1
for i in d:
if d[i]>1:
print(i)
d = {}
for i in range(len(a)):
if(a[i] not in d):
d[a[i]]=1
else:
d[a[i]]=d[a[i]]+1
for i in d:
if d[i]>1:
print(i)
Comments
Post a Comment