繁体   English   中英

用日期格式在Java中拆分字符串

[英]String split in Java with a date format

我有如下字符串:

other data 1 - 2015/04/20, San Francisco
other data 2 - 2015/11/17, Singapore

我想去旧金山和新加坡。 有什么建议么?

String s = "other data 1 - 2015/04/20, San Francisco
";
String city = s.replace(".* [12][0-9]{3}/[0-9]{2}/[0-9]{2}, ", "");

您可以执行以下操作:

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数组供您选择。

因此,以下将起作用:

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);

假设城市永远是字符串中的最后一个信息,则可以使用split函数

string sf="other data 1 - 2015/04/20, San Francisco";
string[] myArray= sf.split(",");
string city= myArray[myArray.length()-1];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM