tiptopjat
tiptopjat

Reputation: 499

Java: replacing characters in a String

I have a String that represents a time value and is stored in the following format:

1:31:25

I would like to replace the colons and change the format to:

1h 31m 25s

What function in Java will let me replace the first two colons with 'h ' and 'm ', and the end of the string with 's'.

Upvotes: 0

Views: 692

Answers (7)

Francisco Spaeth
Francisco Spaeth

Reputation: 23893

You could do something like this:

String[] s = myString.split(":");
String.format("%sh %sm %ss", s);

Or even compact!

String.format("%sh %sm %ss", myString.split(":"));

Upvotes: 8

ewan.chalmers
ewan.chalmers

Reputation: 16235

You can use a regular expression and substitution:

    String input = "1:31:25";
    String expr = "(\\d+):(\\d+):(\\d+)";
    String substitute = "$1h $2m $3s";
    String output = input.replaceAll(expr, substitute);

An alternative is to parse and output the String through Date:

    DateFormat parseFmt = new SimpleDateFormat("HH:mm:ss");
    DateFormat displayFmt = new SimpleDateFormat("H'h' mm\'m' ss's'");
    Date d = parseFmt.parse(input);
    output = displayFmt.format(d);

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272207

Repeated use of the String.replaceFirst() method would help you here.

Simply replace your first ':' with the 'h', then apply again for 'm' etc.

There are additional options, which may be more appropriate/robust etc. depending on your circumstances.

Regular expressions may be useful here, to help you parse/split up such a string.

Or given that you're parsing/outputting times, it may also be worth looking at SimpleDateFormat and its ability to parse/output date/time combinations.

In fact, if you're storing that date as a string, you may want to revist that decision. Storing it as a date object (of whatever variant) is more typesafe, will protect you against invalid values, and allow you to perform arithmetic etc on these.

Upvotes: 2

Sabbath
Sabbath

Reputation: 91

String[] timeStr = "1:31:25".split(":");
StringBuffer timeStrBuf = new StringBuffer();
timeStrBuf.append(timeStr[0]);
timeStrBuf.append("h ");
timeStrBuf.append(timeStr[1]);
timeStrBuf.append("m ");
timeStrBuf.append(timeStr[2]);
timeStrBuf.append("s");

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Use split()

String s = "1:31:25";
String[] temp = s.split(":");
System.out.println(s[0]+"h"+" "+s[1]+"m"+" "+s[2]+"s");

Upvotes: 0

juergen d
juergen d

Reputation: 204746

String input = "1:31:25";
String[] tokens = input.split(":");
String output = tokens[0] + "h " + tokens[1] + "m " + tokens[2] + "s";

Upvotes: 2

Gustav Barkefors
Gustav Barkefors

Reputation: 5086

String time = "1:31:25";
String formattedTime = time.replaceFirst(":","h ").replaceFirst(":","m ").concat("s");

Upvotes: 2

Related Questions