PDA

View Full Version : Splitting a string into two string


dsylebee
06-27-2009, 01:13 AM
hi all I have many strings and its like this

word1,word2

I would like to make a sort of split method which would store word1 into a string and word2 in a string


String stringToCut = "word1, phrase is here";
String s1, s2;

// seperated by the , :)


s1 = manage a way to store the first half in here;
s2 = manage to store the second half in here;


I cant use spaces and read next string cause the second string sometimes has spaces. thnx in advance.

shyam
06-27-2009, 04:05 PM
You can use the StringTokenizer (http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html) or the String's split (http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)) method

dsylebee
06-28-2009, 04:18 AM
You can use the StringTokenizer (http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html) or the String's split (http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)) method

can you illustrate this in a short code. :)

Jimbooo
06-28-2009, 11:03 AM
String stringToCut = "word1, phrase is here";
String s1, s2;

// seperated by the , :)
String[] splittedString = stringToCut.split();

s1 = splittedString[0].trim();
s2 = splittedString[1].trim();


or


String s1, s2;
StringTokenizer stringTokenizer = new StringTokenizer("word1, phrase is here", ",");

String[] splittedString = new String[stringTokenizer.countTokens()];
int i = 0;

while (stringTokenizer.hasMoreTokens()) {
splittedString[i] = stringTokenizer.nextToken();
i++;
}

s1 = splittedString[0].trim();
s2 = splittedString[1].trim();