Home Java Java-tips Data Strings 96string_examples Java: Example - Words to array

Ask Questions?

View Latest Questions

Advertisement


 
 

Java: Example - Words to array
Posted on: February 7, 2008 at 12:00 AM
Java: Example - Words to array

Java: Example - Words to array

This example shows how to convert words to an array.

We will use StringTokenizer to achieve the this.

 

Some times is is required to words into an array, to solve this you can use the StringTokenizer class to get the array of words.

 

The StringTokenizer class is used to break a string into tokens.

 

For converting string into words you can use the space " " as token.

 

 

Following example code shows how to do this.

 

 

 

 

 

 

  
//-------------------------------------------------- stringToArray()
// Put all "words" in a string into an array.
String[] stringToArray(String wordString) {
    String[] result;
    int i = 0;     // index into the next empty array element
    
    //--- Declare and create a StringTokenizer
    StringTokenizer st;
    st = new StringTokenizer(wordString);
    
    //--- Create an array which will hold all the tokens.
    result = new String[st.countTokens()];
    
    //--- Loop, getting each of the tokens
    while (st.hasMoreTokens()) {
        result[i++] = st.nextToken();
    }
    
    return result;
}
Copyleft 2003 Fred Swartz MIT License, Last update: 2003-10-29
Advertisement


DMCA.com