通过键盘在java中拆分字符串

时间:2013-07-25 05:31:48

标签: java string split

我正在编写一个代码,我想在其中拆分以下字符串:

String str = "{route=Head west on, some address, distance=0.2 km, duration=1 min}";

我想分开路线,距离和持续时间的值。

3 个答案:

答案 0 :(得分:1)

尝试这样的事情

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

答案 1 :(得分:1)

您可以使用正则表达式分割字符串:

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)而无需更改代码!

答案 2 :(得分:0)

尝试使用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]);
  }
     

}

希望这对你有用。