Reputation: 1405
I want to get a string count any letter in the string how many time it's appeared in the string,and print the letter and the number So that what i did:
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
String str;
Scanner in = new Scanner(System.in);
System.out.println("enter name");
str = in.nextLine();
char[] c1 = str.toCharArray();
int[] f = new int[str.length()];
for(int i=0;i<str.length();i++) {
for(int j=0;j<str.length();j++) {
if(c1[i]==c1[j]) {
f[i]++;
}
}
}
for(int k=0;k<c1.length;k++) {
for(int l=0;l<c1.length;l++) {
if(c1[k]==c1[l]) {
if(l!=k) {c1[k]=0;f[k]=0;}
}
}
System.out.println(c1[k]+"="+f[k]);
}
}
}
There are two problems:
1. when i print it's printing the duplicated letter twice(or thrice or more depends how many times the letter is in the string).
so i added the another 2 loops(k and l) that deletes the duplicated letters,but now instead of the duplicated letter it's print me: an square and a zero,how i can just get delete the letter and the number from the char and int array's?(for example when i insters the name "elichai" i get:
e=1
l=1
(an square)=0
c=1
h=1
a=1
i=2
2.The letter it deletes is the second letter not the first
(in "elichai" example it's deleted the first 'i' instead of the second 'i')
Thanks!
Upvotes: 0
Views: 2291
Reputation: 1
class Twice_Occuring
{
void main(String s)
{
int count=0;
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
int ind1=s.indexOf(c,i);
int ind2=s.indexOf(c,i+1);
if(ind2-ind1==1)
{System.out.print(c+" ");count++;}
}
System.out.println("\n Number of counts = "+count);
}
}
Upvotes: 0
Reputation: 37813
Different approach to solve your problem, but this is how I would probably do it:
String input = "Whatever";
Map<Character, Integer> charCounter = new LinkedHashMap<>(); // respects insertion order
for (char c : input.replaceAll("\\s+", "").toCharArray()) { // ignore spaces
Integer count = charCounter.get(c);
count = count == null ? 0 : count;
charCounter.put(c, count + 1);
}
System.out.println(charCounter);
Upvotes: 7