String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
Anda mungkin ingin menghapus spasi ke String kedua:
separated[1] = separated[1].trim();
Jika Anda ingin membagi string dengan karakter khusus seperti titik (.), Anda harus menggunakan karakter escape \ sebelum titik
Contoh:
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"
Ada cara lain untuk melakukannya. Misalnya, Anda dapat menggunakan StringTokenizer
kelas (dari 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