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?
android split string by comma
String data = "1,Diego Maradona,Footballer,Argentina";
String[] items = data.split(",");
for (String item : items)
{
System.out.println("item = " + item);
}
String s = "String="
String[] str = s.split("="); //now str[0] is "hello" and str[1] is "goodmorning,2,1"
add this string
.split method will work, but it uses regular expressions. In this example it would be (to steal from Cristian):
String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
Also, this came from: Android split not working correctly
You might also want to consider the Android specific TextUtils.split() method.
The difference between TextUtils.split() and String.split() is documented with TextUtils.split():
String.split() returns [''] when the string to be split is empty. This returns []. This does not remove any empty strings from the result.
I find this a more natural behavior. In essence TextUtils.split() is just a thin wrapper for String.split(), dealing specifically with the empty-string case. The code for the method is actually quite simple.
String s = "having Community Portal|Help Desk|Local Embassy|Reference Desk|Site News";
StringTokenizer st = new StringTokenizer(s, "|");
String community = st.nextToken();
String helpDesk = st.nextToken();
String localEmbassy = st.nextToken();
String referenceDesk = st.nextToken();
String siteNews = st.nextToken();
Source: Stackoverflow.com