RitinMalhotra

Extract Words From a Sentence - Different Method

Oct 29th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. /**
  2.  * Program to extract words from a sentence using a different method.
  3.  */
  4. import java.util.*;
  5. public class GetWords
  6. {
  7.     static ArrayList<String> getWords(String sent) //Method to get the words of a sentence.
  8.     {
  9.         //Variables in this function.
  10.         ArrayList<String> list = new ArrayList<String>();
  11.         String a = " "+sent+" "; //Adding a space before and after a sentence.
  12.         String substr = "";
  13.         String word = "";
  14.         int i;
  15.         char x;
  16.         //Starting the loop.
  17.         for(i=0;i<a.length();i++)
  18.         {
  19.             x = a.charAt(i);
  20.             if(x == ' ')
  21.             {
  22.                 substr = a.substring(i+1); //Creating a substring from the first letter after the space.
  23.                 word = substr.substring(0,(substr.indexOf(" ") + 1)); //Word = substring from the first letter to the first space of substr.
  24.                 list.add(word);
  25.             }
  26.         }
  27.        
  28.         return list;
  29.     }
  30.    
  31.     static void display(ArrayList<String> list) //Method to display the ArrayList of words.
  32.     {
  33.         int i;
  34.         for(i=0;i<list.size()-2;i++)
  35.         {
  36.             System.out.println((i+1) + ")" + list.get(i));
  37.         }
  38.         System.out.println((i+1) + ")" + list.get(list.size()-2));
  39.     }
  40.    
  41.     public static void main(String[] args)
  42.     {
  43.         Scanner sc = new Scanner(System.in);
  44.         System.out.println("Please enter a sentence.");
  45.         String a = sc.nextLine();
  46.         ArrayList<String> list = new ArrayList<String>();
  47.         list = getWords(a);
  48.         System.out.println("Words:");
  49.         display(list);
  50.         sc.close();
  51.     }
  52. }
Add Comment
Please, Sign In to add comment