Guest User

Untitled

a guest
Apr 26th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1.  
  2. public class Haeufigkeiten {
  3.  
  4. /**
  5. *
  6. * @param srcString
  7. * @return
  8. */
  9. public static int[] countOccurances(String srcString){
  10. /*
  11. alloc an array with 65536 places (one for each possible unicode
  12. character). Java initializes each place to 0.
  13. */
  14. int[] resultArray = new int[65536];
  15.  
  16. // helper vars, only i is really needed, we use the others for readability
  17. int i = 0;
  18. int idx;
  19. char currentChar;
  20.  
  21. // loop over each char in the source string
  22. for (; i < srcString.length(); i++){
  23. // get current char
  24. currentChar = srcString.charAt(i);
  25.  
  26. // cast char to int, to get the ascii/unicode number
  27. idx = (int)currentChar;
  28.  
  29. // increment counter at the specific place
  30. resultArray[idx] += 1;
  31. }
  32.  
  33. return resultArray;
  34. }
  35.  
  36. public static void listOccurences(int[] resultArray){
  37. int i = 0;
  38.  
  39. for (; i < resultArray.length; i++){
  40. if (resultArray[i] != 0)
  41. System.out.printf("Character '%c' found %d times.\n", i, resultArray[i]);
  42. }
  43. }
  44.  
  45. public static int characterOccuredHowManyTimes(int[] resultArray,
  46. char character){
  47. return resultArray[(int) character];
  48. }
  49.  
  50. /**
  51. * @param args
  52. */
  53. public static void main(String[] args) {
  54. int[] results;
  55. results = countOccurances("teststring");
  56. listOccurences(results);
  57. System.out.printf("Character t occured %d times.\n",
  58. characterOccuredHowManyTimes(results, 't'));
  59. System.out.printf("Character z occured %d times.\n",
  60. characterOccuredHowManyTimes(results, 'z'));
  61. }
  62.  
  63. }
Add Comment
Please, Sign In to add comment