Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. /**
  2. * Created by forester on 08.11.15.
  3. */
  4. public class Run {
  5. public static void main(String[] args) {
  6. String oneWord = "hello";
  7. String twoWordsSpace = "hello world";
  8. String twoWordsUnderscore = "hello_world";
  9. String allCases = "__ hello _ from demo tests123 __ ";
  10.  
  11. countWordLengths(oneWord);
  12. System.out.println();
  13. countWordLengths(twoWordsSpace);
  14. System.out.println();
  15. countWordLengths(twoWordsUnderscore);
  16. System.out.println();
  17. countWordLengths(allCases);
  18. }
  19.  
  20. public static void countWordLengths(String str) {
  21. if (str.isEmpty())
  22. return;
  23.  
  24. boolean prevCharIsSpace = isSpaceCharacter(str.charAt(0));
  25. int counter = prevCharIsSpace ? 0 : 1;
  26. String word = prevCharIsSpace ? "" : "" + str.charAt(0);
  27.  
  28. for (int i = 1; i < str.length(); i++) {
  29. boolean curCharIsSpace = isSpaceCharacter(str.charAt(i));
  30.  
  31. if (i == str.length() - 1) {
  32. counter = curCharIsSpace ? counter : counter + 1;
  33. word += curCharIsSpace ? "" : "" + str.charAt(i);
  34.  
  35. if (counter != 0) {
  36. System.out.println(word + ":" + counter);
  37. }
  38. } else if (curCharIsSpace && !prevCharIsSpace) {
  39. System.out.println(word + ":" + counter);
  40. counter = 0;
  41. word = "";
  42. } else if (!curCharIsSpace) {
  43. counter++;
  44. word += str.charAt(i);
  45. }
  46.  
  47. prevCharIsSpace = curCharIsSpace;
  48. }
  49. }
  50.  
  51. public static boolean isSpaceCharacter(char c)
  52. {
  53. for (int i = 0; i < SPACE_CHARS.length; i++) {
  54. if (SPACE_CHARS[i] == c)
  55. return true;
  56. }
  57.  
  58. return false;
  59. }
  60.  
  61. private static final char SPACE_CHARS[] = {' ', '_'};
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement