0

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");
Anish B.
  • 7,321
  • 3
  • 12
  • 33

4 Answers4

2

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.

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
0

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();
Sweeper
  • 145,870
  • 17
  • 129
  • 225
  • Showing the `LocalTime` solution is good. For hour within AM or PM you need lowercase `hh` in your format pattern string (or parsing will probably fail when you try to parse `12:45:19AM` or `01:45:19PM`). – Ole V.V. Jul 11 '19 at 11:38
  • Mnemonic: Small `h`is for the small numbers, up to 12. big `H` for the numbers up to 23. The rule works for `d`/`D`and `n`/`N` too, but there are many other examples where it doesn’t. For `m`/`M` you rather need to think of a month as larger than a minute, for example. – Ole V.V. Jul 11 '19 at 11:47
0

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 
Anish B.
  • 7,321
  • 3
  • 12
  • 33
0
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();