Write a Java method to count all words in a string


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.Scanner;
  2. public class Javaexcercise {
  3.  
  4. public static void main(String[] args)
  5. {
  6. Scanner in = new Scanner(System.in);
  7. System.out.print("Enter the string: ");
  8. String str1 = in.nextLine();
  9.  
  10. System.out.print("Number of words in the string: " + countWords(str1)+"\n");
  11. }
  12.  
  13. public static int countWords(String str1)
  14. {
  15. int count = 0;
  16. if (!(" ".equals(str1.substring(0, 1))) || !(" ".equals(str1.substring(str1.length() - 1))))
  17. {
  18. for (int i = 0; i < str1.length(); i++)
  19. {
  20. if (str1.charAt(i) == ' ')
  21. {
  22. count++;
  23. }
  24. }
  25. count = count + 1;
  26. }
  27. return count; // returns 0 if string starts or ends with space " ".
  28. }
  29. }

Result

java techstudy.org

     





Related Topics




Popular Posts