Guest User

Untitled

a guest
Jul 16th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. public static int countWords(String s){
  2.  
  3. int counter = 0;
  4.  
  5. boolean word = false;
  6. int endOfLine = s.length() - 1;
  7.  
  8. for (int i = 0; i < s.length(); i++) {
  9. // if the char is letter, word = true.
  10. if (Character.isLetter(s.charAt(i)) == true && i != endOfLine) {
  11. word = true;
  12. // if char isnt letter and there have been letters before (word
  13. // == true), counter goes up.
  14. } else if (Character.isLetter(s.charAt(i)) == false && word == true) {
  15. counter++;
  16. word = false;
  17. // last word of String, if it doesnt end with nonLetter it
  18. // wouldnt count without this.
  19. } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
  20. counter++;
  21. }
  22. }
  23. return counter;
  24. }
  25.  
  26. int CountWords (String in) {
  27. String[] words = in.split(" "); //separate string around spaces
  28. return words.length();
  29. }
Add Comment
Please, Sign In to add comment