Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

how to decompose a string into words in Java

import java.util.*;
public class CodeGrepper {
    public static void main(String[] args) {
        String strToDecompose = "Some sample text";
        // Use Scanner class to decompose String
        Scanner scan = new Scanner(strToDecompose);
        // hasNext(): return trues if there are more words 
        // next(): retrieves the next word
        while(scan.hasNext()) 
            System.out.print(scan.next() + "/"); // Some/sample/text/
        scan.close();
        System.out.println();
        // Using StringTokenizer to decompose String
        StringTokenizer st = new StringTokenizer(strToDecompose);
        // hasMoreTokens(): return true if there are more words
        // nextToken(): retrieves the next word
        while(st.hasMoreTokens())
            System.out.print(st.nextToken() + "/"); // Some/sample/text/ 
    }
}
 
PREVIOUS NEXT
Tagged: #decompose #string #words #Java
ADD COMMENT
Topic
Name
5+3 =