Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 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. String word = "" + str.charAt(0);
  25. boolean prevCharIsSpace = isSpaceCharacter(str.charAt(0));
  26. int counter = prevCharIsSpace ? 0 : 1;
  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. }
  39.  
  40. if (prevCharIsSpace && curCharIsSpace) {
  41. continue;
  42. } else if ((!prevCharIsSpace && !curCharIsSpace) || (curCharIsSpace && !prevCharIsSpace)) {
  43. if (!curCharIsSpace) {
  44. counter++;
  45. word += str.charAt(i);
  46. }
  47.  
  48. prevCharIsSpace = curCharIsSpace;
  49. } else if ((!prevCharIsSpace && curCharIsSpace) || (!curCharIsSpace && prevCharIsSpace)) {
  50. if (counter != 0) {
  51. System.out.println(word + ":" + counter);
  52. }
  53.  
  54. counter = curCharIsSpace ? 0 : 1;
  55. word = curCharIsSpace ? "" : str.charAt(i) + "";
  56. prevCharIsSpace = curCharIsSpace;
  57. }
  58. }
  59. }
  60.  
  61. public static boolean isSpaceCharacter(char c)
  62. {
  63. for (int i = 0; i < SPACE_CHARS.length; i++) {
  64. if (SPACE_CHARS[i] == c)
  65. return true;
  66. }
  67.  
  68. return false;
  69. }
  70.  
  71. private static final char SPACE_CHARS[] = {' ', '_'};
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement