1

I'm trying to obtain the values of a String, which is separated by commas.

something like this: String str = "item1, item2,0 item3, item4, 0 item5 ...." This strange String it's because I have a KML that I take the coordinates of a polygon parsing the kml. Example: <coordinates> 2.18954459419779,41.40492402705473,0 2.189651379989959,41.40491712193686,0 2.189993453581252,41.40464878075789, ....

What i done to separate it, is:

 List<String> items = Arrays.asList(str.split("\\s*,\\s*"));

But I don't know how to make that this 0 disappears o put a comma between the 0 and the next number.

How can I do it?


Edit: Solution

Testing the answers, what it works perfect to my problem is this solution:

String[] str_solution = str.split("\\s*,0?\\s*");

4 Answers 4

3

Just add the optional zero to the split pattern

"\\s*,0?\\s*"

If it's there it will be splitted with the rest, if not it'll just be ignored.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, that should consider even more cases, nice catch
Thats Perfect!, it separates all "double" numbers, and ignore the 0's . Lot of thanks to both ;)
1
public class Test {
    public static void main(String[] args) {
        String data= "2.18954459419779,41.40492402705473,0 2.189651379989959,41.40491712193686,0 2.189993453581252,41.40464878075789,43.9919";
        String[] dtx = data.split(",");
        for (int j = 0; j < dtx.length; j++) {
            if(dtx[j].indexOf(' ')>=0) dtx[j] = dtx[j].split(" ")[1];   
            System.out.println("data["+j+"]="+dtx[j]);
        }
    }

}

Result

data[0]=2.18954459419779
data[1]=41.40492402705473
data[2]=2.189651379989959
data[3]=41.40491712193686
data[4]=2.189993453581252
data[5]=41.40464878075789
data[6]=43.9919

Comments

1

Please use the following code

String a = "item1, item2,0 item3, item4, 0 item5";
String[] arr = a.split(",|,0|, 0|, 0 |")

This will match ',0' ', 0' and ' , 0 ' and will split accordingly.

Comments

0

use the method split from the String

an example that i have tested:

  String contenido = "item1,item2,item3";
    String[] palabras;

    palabras = contenido.split(",");

    for(int i = 0; i < palabras.length; i++){
        System.out.println(palabras[i]+ " ");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.