簡體   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