我正在编写一个代码,我想在其中拆分以下字符串:
String str = "{route=Head west on, some address, distance=0.2 km, duration=1 min}";
我想将路线、距离和持续时间的值分开。
尝试这样的事情
String str = "{route=Head west on, some address, distance=0.2 km, duration=1 min}";
String newStr=str.replaceAll("\\}","");
String[] arr=newStr.split("route=");
String[] arr1=arr[1].split("distance=");
String route=arr1[0];
String[] arr2=arr1[1].split("duration=");
String distance=arr2[0];
String duration=arr2[1];
System.out.println("route= "+route);
System.out.println("distance= "+distance);
System.out.println("duration= "+duration);
您可以使用正则表达式来拆分字符串:
String str = "{route=Head west on, some address, distance=0.2 km, duration=1 min}";
String regEx = "(\\{route=|distance=|duration=|\\})";
// String regEx = "(route=|distance=|duration=)";
String[] splited = str.split(regEx);
for(String s: splited) {
System.out.println(s);
}
您可以添加任何其他关键字(只需将其添加到 regEx)而无需更改代码!
尝试使用StringTokenizer
来拆分字符串,如下所示:
final String SPLIT_STR = ","; String str = "{route=Head west on, some address, distance=0.2 km, duration=1 min}"; final StringTokenizer stToken = new StringTokenizer( str, SPLIT_STR); final String[] splitStr = new String[stToken.countTokens()]; int index = 0; while(stToken.hasMoreElements()) { splitStr[index++] = stToken.nextToken(); } for(index=0; index < splitStr.length; index++) { System.out.println("Tokenizer : " + splitStr[index]); }
}
希望这对你有用。