1

I have a string as an input eg. Testerty. I want to find the count of each alphabet in the string. I have tried using a HashMap. But I want to implement this using array. Can you please suggest some way.

1
  • 1
    why you want to use array instead of other collection f/ws???Explain question properly. Commented Dec 11, 2011 at 2:49

5 Answers 5

2

You can use ASCII to assign the letters number values: enter image description here

int[] letters = new int[128]; // There are 128 different possible characters.

for(int i = 0; i < input.length; i++) {
    char current = input.charAt(i);
    int index = Character.getNumericValue(char);
    letters[index]++;
}
Sign up to request clarification or add additional context in comments.

Comments

1
ArrayList<Character> ch = new ArrayList<Character>();
ArrayList<Integer> count = new ArrayList<Integer>();

someMethod(String input) {
  for(char c : input.toCharArray()) {
    if(ch.indexOf(c) != -1) {
      i.set(ch.indexOf(c), i.get(ch.indexOf(c))+1);
    } else {
      ch.add(c);
      i.add(1);
    }
  }
}

1 Comment

We need a key=value pair, not a list of values.
1

doing it with a Map is easier, where the letters are keys and the values are counts. Using an array is more tricky; you could assign each letter a number, and use that number as an index into the array, and store the counts in the array. So 'A' is 1, 'B' is 2, etc....The algorithm is

  1. Get next letter of string.
  2. Get the index for the letter.
  3. Increment the value at that index in the array by 1.

Of course you need to do null checking and whatever.

Note that this is logically a Map. It's just when you use a Map, the Map does step 2 above for you.

Comments

1

You should use a collection implementing Multiset iunterface, i.e. HashMultiset (both taken from Google Guava library). Multiset is designed to hold counts for objects in collection:

Multiset<String> m = HashMultiset.create(Arrays.asList("a", "a", "b", "c", "b", "a"));
// m.toString() prints "a x 3, b x 2, c x 1"
// m.count() gives 6

Comments

1

One way could be, you first create an array, then traverse string using charAt(index) method ,match the current char against those in the array.If you find the match ,increment the value there,or add it as a new entry in the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.