Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Haeufigkeiten {
- /**
- *
- * @param srcString
- * @return
- */
- public static int[] countOccurances(String srcString){
- /*
- alloc an array with 65536 places (one for each possible unicode
- character). Java initializes each place to 0.
- */
- int[] resultArray = new int[65536];
- // helper vars, only i is really needed, we use the others for readability
- int i = 0;
- int idx;
- char currentChar;
- // loop over each char in the source string
- for (; i < srcString.length(); i++){
- // get current char
- currentChar = srcString.charAt(i);
- // cast char to int, to get the ascii/unicode number
- idx = (int)currentChar;
- // increment counter at the specific place
- resultArray[idx] += 1;
- }
- return resultArray;
- }
- public static void listOccurences(int[] resultArray){
- int i = 0;
- for (; i < resultArray.length; i++){
- if (resultArray[i] != 0)
- System.out.printf("Character '%c' found %d times.\n", i, resultArray[i]);
- }
- }
- public static int characterOccuredHowManyTimes(int[] resultArray,
- char character){
- return resultArray[(int) character];
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- int[] results;
- results = countOccurances("teststring");
- listOccurences(results);
- System.out.printf("Character t occured %d times.\n",
- characterOccuredHowManyTimes(results, 't'));
- System.out.printf("Character z occured %d times.\n",
- characterOccuredHowManyTimes(results, 'z'));
- }
- }
Add Comment
Please, Sign In to add comment