我的字符串如下:
other data 1 - 2015/04/20, San Francisco
other data 2 - 2015/11/17, Singapore
我想要旧金山和新加坡。有什么建议吗?
答案 0 :(得分:1)
String s = "other data 1 - 2015/04/20, San Francisco
";
String city = s.replace(".* [12][0-9]{3}/[0-9]{2}/[0-9]{2}, ", "");
答案 1 :(得分:0)
您可以执行以下操作:
String sf = "other data 1 - 2015/04/20, San Francisco"
String city = sf.substring(27);
这假设您每次获得一行,并且格式始终相同。
有关子字符串的更多信息:https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)
<强> 更新 强>
我以为你只想要那两个字符串。
另一种解决此问题的方法是使用split,它将返回一个字符串数组供您选择。
以下内容将起作用:
String sf = "other data 1 - 2015/04/20, San Francisco";
String[] chunks = sf.split(',');
String city= chunks[chunks.length - 1].substring(1);
子字符串仍然存在,因为在您分割逗号后,将会有您要删除的额外空格。
有关拆分的更多信息:https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
另一种方法是合并indexOf()
。
String sf = "other data 1 - 2015/04/20, San Francisco"
int commaIndex = sf.indexOf(',');
String city = sf.substring(commaIndex + 2);
答案 2 :(得分:0)
假设城市始终是字符串中的最后一个信息,您可以使用拆分功能
string sf="other data 1 - 2015/04/20, San Francisco";
string[] myArray= sf.split(",");
string city= myArray[myArray.length()-1];