Daniel said:
IchBin said:
Angus said:
Hello
I have a semi-colon delimited string eg
apple;pear;banana;pineapple; and want to extract each 'element' of
the string. All I really want to do is print each individual
element. But when I get the code working I want to use in a Java
applet so only want to use up to Java 1.1
How would I achieve this?
Angus
Try using String split(). The last I heard Sun was trying to move
away from StringTokenizer to this string function. Example:
String target = "apple;pear;banana;pineapple;";
String[] data = target.split(";");
for (String item : data)
System.out.println(item );
Except, the OP specifically said Java 1.1, and split is relatively
knew.
Having said that, there is usually no good reason to stay with Java
1.1 these days, he should indeed use split for the simple case.
Here's a function I used in a 1.1 applet once...
/**Splits a string into a list of strings
* @param - source, String original string to be split
* @param - splitAt, token to split at
* @return - Returns a String array containing the sub elements
*/
protected String[] split(String source, String splitAt)
{
int cElements = 0;
for (int i = 0; i < source.length(); i++)
{
if(source.charAt(i) == splitAt.charAt(0))
cElements+=1;
}
String tmpResult[] = new String[cElements+1];
int prevIndex = 0;
for(int i = 0; i <= cElements; i++)
{
int curIndex = source.indexOf(splitAt,prevIndex+1);
if(curIndex == -1)
curIndex = source.length();
tmpResult
= new String(source.substring(prevIndex !=0 ? prevIndex+1
: prevIndex , curIndex));
prevIndex = curIndex;
}
return tmpResult;
}
....
String target = "apple;pear;banana;pineapple;";
String[] data = target.split(target,";");
for (int i=0; i<data.length; i++)
System.out.println(data);