Answers:
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
etPhoneNo.getText().toString().replaceAll("\\D", "");
它说替换掉所有不是数字的东西
.split方法可以使用,但是使用正则表达式。在此示例中,将是(从Cristian窃取):
String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
另外,这来自于: Android split无法正常工作
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();
您可能还需要考虑Android特定的TextUtils.split()方法。
TextUtils.split()和TextUtils.split()之间的区别在于:
当要拆分的字符串为空时,String.split()返回[“]。返回[]。这不会从结果中删除任何空字符串。
我发现这是一种更自然的行为。本质上,TextUtils.split()只是String.split()的一个薄包装,专门处理空字符串的情况。该方法的代码实际上非常简单。
String s =“ String =”
String [] str = s.split(“ =”); //现在,str [0]是“ hello”,str [1]是“ goodmorning,2,1”
添加这个字符串