Almac
Almac

Reputation: 227

Count the occurrence of every alphabet from a string

I know this topic has been covered before, but I'm not finding what I need. I'm trying to count the occurrence of every letter from the alphabet; from a user inputed string. The output will include all 26 letters, even if they do not occur. So a 0 will be assigned to the non-occurring letter. I'm doing this by looping through an array of alphabets and comparing it to the user input.

I'm having trouble adding the letters and displaying every letter. My output results in displaying every letter inputed + 1.

    public class TwoArrays {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        char[] lower = new char[] {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        char[] upper = new char[] {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

        System.out.println("Please enter a sentence to parse.");
        String userString = input.nextLine();

        for(int i = 0; i < userString.length(); i++) {
            //lowercase
            for(int l = 0; l < lower.length; l++) {
                int counter = 0;
                if(lower[l] == userString.charAt(i)) {
                    counter++;
                    System.out.println(lower[l] + ":" + counter);
                }
            }   
            //uppercase
            for(int u = 0; u < upper.length; u++) {
                int counter = 0;
                if(upper[u] == userString.charAt(i)) {
                    counter++;
                    System.out.println(upper[u] + ":" + counter);
                }
            }
        }
    }
}

Output

Please enter a sentence to parse.
hello WORLD
h:1
e:1
l:1
l:1
o:1
W:1
O:1
R:1
L:1
D:1

Upvotes: 1

Views: 11218

Answers (7)

amit jaiswal
amit jaiswal

Reputation: 1

here is the simplest answer without using any package...

here i have a string, first of all i am converting this string to chararray then i ran a loop to count number of alphabets in the this chararray.

As each alphabet occurs at least once so i have assigned 1 to a flag c that stores number of occurrence of each alphabet.

Now i ran nested loop to check whether an alphabet occurs more than once..if it does occur, i increment flag c by 1 and then i am running third nested loop from k=j to delete this repeated alphabet...

here j is the index of repeated alphabet and to delete this alphabet i am assigning value at next ( j+1 ) index to this ( j ) index and value at index j+2 is assigned to the index j+1....and so on until i reached at n-1 index which is now assigned value of nth index.

After deleting this repeated alphabet, size of chararray is reduced by 1 so i decremented n by 1.

    public class AlphabetOccurance {
public static void main(String[] args) {
    String s;
    s = "ASGFDTRRCJFYDCJHGJ";
    char ch[] = s.toCharArray(); // converted string to chararray       
     int i,j,k,c=1,n;
     for (i=0; i<s.length();i++); // loop to find no. of alphabet in string
     n=i;
     System.out.println("number of charaters in string = " + n); 
     for (i=0; i<n;i++)
     {
        for (j=i+1; j<n ;j++)
        {
            if (ch[j] == ch[i]) //if an alphabet if repeated...
            {
                c++; // if repeated alphabet found, increment count by 1

                for (k=j; k<n-1;k++) //loop to delete repeated alphabet
                {
                    ch[k] = ch[k+1];//deleting repeated alphabet
                }
             n--; // after deleting repeated alphabet, n is decremented by 1
            }
         }
       System.out.println("alphabet " + ch[i] + " occured " + c + " times");

       c=1; // for counting of next alphabet, now initialized c back to 1
     }  
}}

Output:

number of charaters in string = 18

alphabet A occured 1 times

alphabet S occured 1 times

alphabet G occured 2 times

alphabet F occured 2 times

alphabet D occured 2 times

alphabet T occured 1 times

alphabet R occured 2 times

alphabet C occured 2 times

alphabet J occured 3 times

alphabet Y occured 1 times

alphabet H occured 1 times

Upvotes: 0

Per-&#197;ke Minborg
Per-&#197;ke Minborg

Reputation: 290

In Java 8 you could solve the problem like this:

    String input = "Hello WORLD";

    Map<Character, Integer> map = new TreeMap<>();

    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
            .chars()
            .mapToObj(i -> (char) i)
            .forEach(c -> map.put(c, 0));

    input.chars()
            .mapToObj(i -> (char) i)
            .forEach(c -> map.computeIfPresent(c, (k, v) -> v + 1));

    System.out.println(map);

This will produce:

{A=0, B=0, C=0, D=1, E=0, F=0, G=0, H=1, I=0, J=0, K=0, L=1, M=0, N=0, O=1, P=0, Q=0, R=1, S=0, T=0, U=0, V=0, W=1, X=0, Y=0, Z=0, a=0, b=0, c=0, d=0, e=1, f=0, g=0, h=0, i=0, j=0, k=0, l=2, m=0, n=0, o=1, p=0, q=0, r=0, s=0, t=0, u=0, v=0, w=0, x=0, y=0, z=0}

Upvotes: 0

Mick Mnemonic
Mick Mnemonic

Reputation: 7956

Using Google Guava's Multiset, you can get rid of the unnecessary boilerplate and calculate a case-sensitive histogram in a one-liner (use input.toLowerCase().toCharArray() for case-insensitivity):

String input = "hello WORLD";
Multiset<Character> histogram = HashMultiset.create(
    Chars.asList(input.toCharArray()));

The histogram can be output like this:

public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
//...
final List<Character> caseSensitiveAlphabet 
    = Lists.newArrayList(Chars.asList(ALPHABET.toCharArray()));
caseSensitiveAlphabet.addAll(
    Chars.asList(ALPHABET.toUpperCase().toCharArray()));

for (char c : caseSensitiveAlphabet) {
    System.out.println(c + " : " + histogram.count(c));
}

Upvotes: 0

Neero
Neero

Reputation: 226

public static void main(String args[]){
    //Convert below lower and upper arrays into one new upperlower map Map<Character, Integer>
    //char[] lower = new char[] {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    //char[] upper = new char[] {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    Map<Character, Integer> countMap = new TreeMap<>();
    Integer count;
    String inputStr = "Hello WORLD";
    char[] arr = inputStr.toCharArray();

    for(Character c : arr){
        count = 0;
        if(c == ' ')
            continue;
        if(countMap.containsKey(c))
            count = countMap.get(c);
        countMap.put(c, count+1);
    }

    Iterator<Entry<Character, Integer>> it = countMap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<Character, Integer> pair = (Map.Entry<Character, Integer>)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        it.remove(); // avoids a ConcurrentModificationException

        /*Check pair.getKey() contains on upperlower map if contains assign the new 
          value into map */

    }

    //Finally loop the upperlower Map to display character occurence
}

Thinks this will helps you.

Upvotes: 0

sam
sam

Reputation: 2033

Here is an approach using hashmap. Since you want to display 0 to char not in the string, we can first put all characters in the map. Then we can iterate over the string and increment value of character found.

Map<Character, Integer> charMap = new HashMap<Character, Integer>();

for (Character c: "abcdefghijklmnopqrstuvwxyz".toCharArray()) {
    charMap.put(c, 0);
}

for (Character c: test.toCharArray()) {
    if (charMap.containsKey(c)) {
        charMap.put(c, charMap.get(c) + 1);
    }
}

Demo

Upvotes: 1

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

Use a enhanced loop + HashMap and you can unify your two char containing arrays :

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    char[] array = new char[] {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

    System.out.println("Please enter a sentence to parse.");
    String userString = input.nextLine();

    HashMap<Character, Integer> charint = new HashMap<>();

    for (Character c : userString.toCharArray()){
        if (charint.containsKey(c)) charint.replace(c, charint.get(c).intValue() + 1);
        else charint.put(c, 1);
    }

    for (int i = 0 ; i < array.length ; i++){
        System.out.println(array[i] + " : " + (charint.get(array[i]) == null ? "0" : charint.get(array[i])));
    }
}

Output

Please enter a sentence to parse.
Hello the world
a : 0
b : 0
c : 0
d : 1
e : 2
f : 0
g : 0
h : 1
i : 0
j : 0
k : 0
l : 3
m : 0
n : 0
o : 2
p : 0
q : 0
r : 1
s : 0
t : 1
u : 0
v : 0
w : 1
x : 0
y : 0
z : 0
A : 0
B : 0
C : 0
D : 0
E : 0
F : 0
G : 0
H : 1
I : 0
J : 0
K : 0
L : 0
M : 0
N : 0
O : 0
P : 0
Q : 0
R : 0
S : 0
T : 0
U : 0
V : 0
W : 0
X : 0
Y : 0
Z : 0

Upvotes: 2

Iłya Bursov
Iłya Bursov

Reputation: 24146

here is case-insensitive version of English alphabet counting app:

public static void main(final String[] args) {
    System.out.println("Please enter a sentence to parse.");
    try (final Scanner input = new Scanner(System.in)) {
        final String userString = input.nextLine();

        final long[] symbols = new long[26];
        for (final char c : userString.toCharArray()) {
            if ((c >= 'a') && (c <= 'z')) {
                symbols[c - 'a']++;
            } else if ((c >= 'A') && (c <= 'Z')) {
                symbols[c - 'A']++;
            }
        }
        for (int i = 0; i < 26; i++) {
            System.out.println((char) ('a' + i) + ": " + symbols[i]);
        }
    }
}

sample output for "hello WORLD":

a: 0
b: 0
c: 0
d: 1
e: 1
f: 0
g: 0
h: 1
i: 0
j: 0
k: 0
l: 3
m: 0
n: 0
o: 2
p: 0
q: 0
r: 1
s: 0
t: 0
u: 0
v: 0
w: 1
x: 0
y: 0
z: 0

Upvotes: 0

Related Questions