SASM
SASM

Reputation: 1312

How to extract the proper String?

I have a string like this:

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

i.e, at the beginning there's a space and also after 0.000000 there's a space. I just want to extract 14.XYZ and 56.XYZ. How can I do this?

Upvotes: 0

Views: 209

Answers (4)

krock
krock

Reputation: 29619

use String.split() to separate each number and then Double.valueOf() to convert it to a 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);
    // ...
}

Upvotes: 0

rjgonzo
rjgonzo

Reputation: 1761

This might not be the most beautiful solution, but it will work.

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

Upvotes: 0

lynks
lynks

Reputation: 5689

This will split, and iterate over all decimals in the input string

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
   }
}

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

As per my comment, try String#split(...), such as:

  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]+" is a regular expression that helps the split method split the String using one or more white space characters (\s) or a comma.

Upvotes: 2

Related Questions