Android Split string

zaid picture zaid · Sep 17, 2010 · Viewed 442.3k times · Source

I have a string called CurrentString and is in the form of something like this "Fruit: they taste good".
I would like to split up the CurrentString using the : as the delimiter.
So that way the word "Fruit" will be split into its own string and "they taste good" will be another string.
And then i would simply like to use SetText() of 2 different TextViews to display that string.

What would be the best way to approach this?

Answer

Cristian picture Cristian · Sep 17, 2010
String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

You may want to remove the space to the second String:

separated[1] = separated[1].trim();

If you want to split the string with a special character like dot(.) you should use escape character \ before the dot

Example:

String currentString = "Fruit: they taste good.very nice actually";
String[] separated = currentString.split("\\.");
separated[0]; // this will contain "Fruit: they taste good"
separated[1]; // this will contain "very nice actually"

There are other ways to do it. For instance, you can use the StringTokenizer class (from java.util):

StringTokenizer tokens = new StringTokenizer(currentString, ":");
String first = tokens.nextToken();// this will contain "Fruit"
String second = tokens.nextToken();// this will contain " they taste good"
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method