asifbro February 2016

How can I make this String counter code more efficient?

Here is my code. Method counter counts the number of times each alphabet occurs in the string.

public class Hard{

public static void counter (String s) {

  for (int n = 0; n < s.length() ; n++) {

       int count = 0 ,bool = 1;

       if (n > 0) {  

          for (int L = n-1 ; L >= 0  ; L--) {
             if (s.charAt(n) == s.charAt(L)) {bool = 0; }         
          }

       }

       for (int f = 0; f < s.length() ; f++ ) {
         if (bool == 0) { break ; }

         if (s.charAt(n) == s.charAt(f)) {count++;}
       }

       if (count > 0 ) {

         System.out.println(s.charAt(n)+" appears "+count+" times.");
       }
  }    

}

 public static void main (String[] args) {
   counter("bbaddadxzxwfgb$.fgfdf");                  
 }

}

Answers


Neil February 2016

Assuming that you're using Java and assuming A and a are counted as the same letter.

public static int[] counter (String s) {
    int [] countArr = new int[26];
    for(int i=0; i<s.length(); i++) {
        char charAtI = s.charAt(i);
        if(Character.isLetter(charAtI)) {
            countArr[Character.isUpperCase(charAtI) ? charAtI - 'A' : charAtI - 'a']++;
        }
    }
    return countArr;
}

public static void main (String[] args) {
    int [] countArr = counter("asif and abid.");
    for(int i = 0; i<countArr.length; i++) {
        if(countArr[i] > 0) {
            System.out.println(MessageFormat.format("{0} appears {1} times", (char)(i + 'a'), countArr[i]));
        }
    }
}

The key to the optimization lies in the fact that it performs one pass with no nested loops and once you have all the information you require, then worry about how to present it to the user.


Ankit Deshpande February 2016

 public static HashMap<Character, Integer> counter(String input) {

    HashMap<Character, Integer> chCount = new HashMap<>();
    for (int i = 0 i < input.length(); i++) {
        char c = input.charAt(i);
        if (chCount.containsKey(c)) {
        int count = chCount.get(c);
        chCount.put(c, count + 1);
        } else {
        chCount.put(c, 1);
        }
    }
    return chCount;
    }

You can use hashmaps as well. It will work for other characters like '#', etc and you can treat 'A' and 'a' differently, because the key value will be different.
HashMap tutorials Point


Noor Nawaz February 2016

You can count chars like this, using java 8

public static void main(String[] args){

        String string="what is this?";
        List<Character> chars=string.chars().distinct().mapToObj(i->Character.valueOf((char)i)).filter(p->Character.isAlphabetic(p)).collect(Collectors.toList());
        chars.forEach(c->{
        long count=string.chars().mapToObj(i->Character.valueOf((char)i)).filter(p->p==c).count();
        System.out.println(c+" appear "+count+" times");
        });
 }


Jason Walker February 2016

I thought about it backwards, I assumed A and a were the same.

public static void counter(String str) {
    String s = str.toLowerCase();
    for (int n = 0; n < s.length(); n++) {
        int count = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == s.charAt(n)) { count++; }
        }
        System.out.println(str.charAt(n) + " appears " + count + " times.");
    }
}

public static void main(String[] args) {
    counter("asif and abid.");
}

Post Status

Asked in February 2016
Viewed 1,509 times
Voted 4
Answered 4 times

Search




Leave an answer