String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
您可能要删除第二个字符串的空格:
separated[1] = separated[1].trim();
如果要使用特殊字符(例如dot(。))分割字符串,则应在点之前使用转义字符\
例:
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"
还有其他方法可以做到这一点。例如,您可以使用StringTokenizer类(来自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