1

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.

0

3 Answers 3

4

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]
Sign up to request clarification or add additional context in comments.

2 Comments

This works but I don't really understand how. Thank you
You just need to familiar with regular expressions @TruongNguyen docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
2

For your problem I might suggest using a formal Java regex matcher. The reason for this is that perhaps your time strings could appear as part of a larger string.

String input = "1:00 pm 2:00 pm 3:00 pm";
String pattern = "(?i)\\d{1,2}:\\d{2} [ap]m";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
     System.out.println("Found a time: " + m.group(0));
}

This prints:

Found a time: 1:00 pm
Found a time: 2:00 pm
Found a time: 3:00 pm

Comments

0

You could use Java's indexOf method to find the index of each space and only take into account every other one. Then, create a sub string using your knowledge of the spaces and add it to your array.

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.