Java: How to convert String to array?
11 February 2009
Sometime you get a string in a fixed format and you want individualise it and store them into array so you can manipulate it easier with your other functions.
For example,
String array = "one,two,three,four,five,six,seven,eight,nine";
will become
String[] words = {one,two,three,four,five,six,seven,eight,nine};
Below code is demonstrating how fixed format string can be broken down and stored into array.
Class: StringToArray.java
/** * Computer-FAQS.com * @author Manet Yim (manet.yim at gmail dot com) * @license: GPL v3.0 */ public class StringToArray { /** * Testing method * @param args */ public static void main(String[] args) { // your raw string in a fixed format String array = "one,two,three,four,five,six,seven,eight,nine"; // converting raw string input array object and display it String[] convertedArray = StringToArray.convert(array, ","); for (int i = 0; i<convertedArray.length; i++){ System.out.println(convertedArray[i]); } } /** * Convert a String s to an Array, where each element in string * seperated by sep * * @param str String to be converted * @param sep Element seperator * @return Array of strings */ public static String[] convert(String str, String sep) { StringBuffer sBuf = new StringBuffer(str); // there is at least one element in the array int aSize = 1; // Counting how many separator in the string // result will be the size of new array for (int i = 0; i < sBuf.length(); i++) { if (sep.indexOf(sBuf.charAt(i)) != -1) aSize++; } // create new array object with predefined size String[] elements = new String[aSize]; int x, y = 0; if (sBuf.indexOf(sep) != -1) { while (sBuf.length() > 0) { if (sBuf.indexOf(sep) != -1) { x = sBuf.indexOf(sep); if (x != sBuf.lastIndexOf(sep)) { elements[y] = sBuf.substring(0, x); y++; sBuf.delete(0, x + 1); } else if (sBuf.lastIndexOf(sep) == x) { elements[y] = sBuf.substring(0, sBuf.indexOf(sep)); y++; sBuf.delete(0, sBuf.indexOf(sep) + 1); elements[y] = sBuf.toString(); y++; sBuf.delete(0, sBuf.length()); } } } } else { elements[0] = sBuf.toString(); } sBuf = null; return elements; } }
525 views

Amazon


I am new here, just curious why the StringTokenizer is not used?
StringTokenizer st = new StringTokenizer(this.wordsToCount);
stringArray = new String[st.countTokens()];
int i =0;
while(st.hasMoreTokens())
{
stringArray[i] = st.nextToken();
i++;
}
Uma, thanks for the comment.
By all means you can use StringTokenizer to implement your own java function.
The implementation of this class in this post was to use only native code (without importing any java generic class) and to demo the algorithm. The same code can be easily translated into another language (which might not have StringTokenizer).