How to turn a string into an array of strings?

Truong Nguyen :

For example, I want a string "1:00 pm 2:00 pm 3:00 pm" to turn into an array of a string of ["1:00 pm", "2:00 pm", "3:00 pm"]

I've tried using split. But it would produce ["1:00", "pm", "2:00", "pm", "3:00", "pm"]. How would I split every other space? Thank you.

Deadpool :

split using regular expression, Regular expression (?<=m) to split the string using m as delimiter and including it. But there will be extra empty character from second element you can use trim() method to remove it

String s =  "1:00 pm 2:00 pm 3:00 pm";

String[] arr = s.split("(?<=m)");

System.out.println(Arrays.toString(arr));   //[1:00 pm,  2:00 pm,  3:00 pm]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328139&siteId=1