0

I am having this string 00 hours 01 minutes 25 seconds stored in variable . How can I convert it into 00:01 hour and minutes in Java

what I tried is:

String s = "00 hours 01 minutes 25 seconds";
System.out.println(s);
String []a = s.split(" , ");
String s2 = a[0] + a[2];
1
  • 2
    1. new is not valid variable name - it is a reserved keyword. 2. You use wrong regex to split your string. Use s.split(" ") instead Commented Jan 15, 2021 at 8:39

2 Answers 2

2

The newS will give the result you want

String s = "00 hours 01 minutes 25 seconds";
System.out.println(s);
String []a = s.split("\\s");
String newS = a[0] + ":" + a[2];
System.out.println(newS);
Sign up to request clarification or add additional context in comments.

5 Comments

String.split uses regex not substrings
Not with all whitespace characters, and the question didn't specify them
@tibetiroka I see your point in using \s instead of " ", but i usualy work with " " and I don't have a problem with that. Can you explain me when it will be a problem?
It might be a problem if your application is used in different regions or with different charsets, not everythink respects the UTF-16 conversion (or the standard ascii whitespace character code), or (if your string is imputted) it will not work with tabulators. However \\s supports any whitespace characters (it is short for the [ \t\n\x0B\f\r] regex). If you want to be really safe, you can use \\s* which matches any number of whitespace characters.
Well thank you very much for the explanation. I will also edit my amswer to use \s
2

Your logic is correct, however your implementation has some issues.

//String.split() uses regular expressions, this will split at spaces
String[] a = s.split("\\s");
String newString = a[0]+":"+a[2];

This should work.

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.