如何提取正确的字符串?

时间:2011-10-08 00:55:31

标签: java string stringtokenizer

我有一个这样的字符串:

 14.809180,56.876968,0.000000 14.808170,56.877048,0.000000 14.805100,56.877220,0.000000 14.804130,56.877338,0.000000

,即在开始时有一个空格,在0.000000之后还有一个空格。我只想提取14.XYZ56.XYZ。我怎么能这样做?

4 个答案:

答案 0 :(得分:2)

根据我的评论,尝试String#split(...),例如:

  String test = "14.809180,56.876968,0.000000 14.808170,56.877048,0.000000 14.805100,56.877220,0.000000";
  String[] tokens = test.split("[,\\s]+");
  for (String token : tokens) {
     System.out.println(token);
  }

"[,\\s]+"是一个正则表达式,可帮助split方法使用一个或多个空格字符(\ s)或逗号分割String。

答案 1 :(得分:0)

使用String.split()分隔每个数字,然后Double.valueOf()将其转换为double

String string = "14.809180,56.876968,0.000000 14.808170,56.877048,0.000000 14.805100,56.877220,0.000000 14.804130,56.877338,0.000000";
String[] numStrings = string.split("[ ,]");
for (String num : numStrings) {
    double d = Double.valueOf(num);
    // ...
}

答案 2 :(得分:0)

这将拆分并迭代输入字符串

中的所有小数
String groups[] = input.split(" ");
for(int i = 0; i < groups.length; i++) {
   String decimals[] = groups[i].split(",");
   for(int j = 0; j < decimals.length; j++) {
      float f = Float.parseFloat(decimals[j]);
      //do something with f
   }
}

答案 3 :(得分:0)

这可能不是最美丽的解决方案,但它会起作用。

String[] myStrings = uglyString.spli(",");
Integer firstNum = new Integer(myStrings[0]);
Integer secondNum = new Integer(myStrings[1]);