Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Program to extract words from a sentence using a different method.
- */
- import java.util.*;
- public class GetWords
- {
- static ArrayList<String> getWords(String sent) //Method to get the words of a sentence.
- {
- //Variables in this function.
- ArrayList<String> list = new ArrayList<String>();
- String a = " "+sent+" "; //Adding a space before and after a sentence.
- String substr = "";
- String word = "";
- int i;
- char x;
- //Starting the loop.
- for(i=0;i<a.length();i++)
- {
- x = a.charAt(i);
- if(x == ' ')
- {
- substr = a.substring(i+1); //Creating a substring from the first letter after the space.
- word = substr.substring(0,(substr.indexOf(" ") + 1)); //Word = substring from the first letter to the first space of substr.
- list.add(word);
- }
- }
- return list;
- }
- static void display(ArrayList<String> list) //Method to display the ArrayList of words.
- {
- int i;
- for(i=0;i<list.size()-2;i++)
- {
- System.out.println((i+1) + ")" + list.get(i));
- }
- System.out.println((i+1) + ")" + list.get(list.size()-2));
- }
- public static void main(String[] args)
- {
- Scanner sc = new Scanner(System.in);
- System.out.println("Please enter a sentence.");
- String a = sc.nextLine();
- ArrayList<String> list = new ArrayList<String>();
- list = getWords(a);
- System.out.println("Words:");
- display(list);
- sc.close();
- }
- }
Add Comment
Please, Sign In to add comment