Showing posts with label split. Show all posts
Showing posts with label split. Show all posts

How to convert a sentence string to a string array of words in java?

Question:
How to convert a sentence string to a string array of words in java?

Answer:
String s = "This is a sample sentence.";
String[] words = s.split("\\s+");

Code:
public class ArrayOfWords {
  public static void main(String[] args) {
 
    String str = "This is an example";
    String[] words = str.split("\\s+");
 
    System.out.println("String: " + str);
 
    for(String word: words) {
      System.out.println(word);
    }
  }
}

Output:
$ java ArrayOfWords
String: This is an example
This
is
an
example

How to count words in a sentence?

Question:
How to count words in a sentence?

Code:
import java.util.*;
 
public class CountWords {
   public static void main(String[] args) {
 
      System.out.print("Enter a string: ");
 
      Scanner sc = new Scanner(System.in);
      String str = sc.nextLine();
 
      String[] words = str.split(" ");
 
      System.out.println("String: " + str);
      System.out.println("Total Words: " + words.length);
 
      sc.close();
   }
}

Output:
$ java CountWords 
Enter a string: To be or not to be
String: To be or not to be
Total Words: 6