Friday, January 22, 2016

Split A Sentence Into Words

This program converts a sentence to an array of words. Date class is used to form the sentence so the array of words will contain day, month, date, and time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.*;

public class DateDemo {
    public static void main(String[] args){
        Date d=new Date();
        String st=d.toString();
        
        int counter=0;
        for(int i=0;i<st.length();i++){
            if(st.charAt(i)==' '){
                counter++;
            }
        }
        
        StringTokenizer stoken=new StringTokenizer(st);        
        ArrayList<String> al=new ArrayList<String>();
        
        for(int i=0;i<counter;i++){
            al.add(i,stoken.nextToken(" "));
            System.out.println(al.get(i));
        }
    }
}


for(int i=0;i<st.length();i++){
     if(st.charAt(i)==' '){
          counter++;
     }
}

Basically, what the 'for' loop does is to count the number of words in the sentence. The value wil be used in the second 'for' loop. Everytime a space is detected, 1 is added to the variable counter.

StringTokenizer stoken=new StringTokenizer(st);

The StringTokenizer class is used to split the string by 'space' delimiter.

for(int i=0;i<counter;i++){
 al.add(i,stoken.nextToken(" "));
        System.out.println(al.get(i));
}

The nextToken() method is used to extract the words in the sentence. Words that have been separated are stored in an ArrayList named "al". Each word is then displayed on the screen.

No comments:

Post a Comment