I am trying to use the split function to remove ": and PM" in the string.
"07:45:19PM"
I want to make 07:45:19PM into 07 45 19
String s = "07:45:19PM"
String heys[] = new String[10];
heys = s.split(":PM");
I am trying to use the split function to remove ": and PM" in the string.
"07:45:19PM"
I want to make 07:45:19PM into 07 45 19
String s = "07:45:19PM"
String heys[] = new String[10];
heys = s.split(":PM");
The flexible high-level solution uses java.time, the modern Java date and time API.
For many purposes you should not want to convert a time from one string format to another. In your program, rather keep a time of day as a LocalTime
object. Just like you keep numbers in int
or double
variables, not strings. When you receive a string, parse it into a LocalTime
first thing. Only when you need to give out a string, format the LocalTime
into the desired string.
Parsing input
DateTimeFormatter givenFormatter = DateTimeFormatter.ofPattern("hh:mm:ssa", Locale.ENGLISH);
String s = "07:45:19PM";
LocalTime time = LocalTime.parse(s, givenFormatter);
Formatting and printing output
DateTimeFormatter wantedFormatter = DateTimeFormatter.ofPattern("hh mm ss");
String wantedString = time.format(wantedFormatter);
System.out.println(wantedString);
Output is:
07 45 19
Tutorial link
Oracle tutorial: Date Time explaining how to use java.time.
split
accepts a regular expression, so you need to use :|PM
to mean "a :
or PM
":
String[] heys = s.split(":|PM");
You don't need to specify the length of keys
because split
will figure that out by itself.
Alternatively, if you actually want to extract the hour, minute, and seconds as integers, you can use LocalTime.parse
:
LocalTime time = LocalTime.parse(s,
DateTimeFormatter.ofPattern("hh:mm:ssa").withLocale(Locale.US));
int hour = time.getHour();
int minute = time.getMinute();
int second = time.getSecond();
Just simply use this code :
String s = "07:45:19PM";
String[] heys = s.split(":");
for(String hey: heys) {
System.out.print(hey.replace("PM", "") + " ");
}
Output :
07 45 19
String s = "07:45:19PM";
String heys[] = s.split(":|PM");
String parsedString = new StringBuilder().append(heys[0]).append(" ").append(heys[1]).append(" ").append(heys[2]).toString();