Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java replace string string by other string

Tags:

java

I want to replace 1 by 1Min, 5 by 5Min, 10 by 10Min, 15 by 15Min,60 by 1Hour, 360 by 6Hours etc.

How can I do it in 1 statement.

String str = "15";
String newStr = str.replace("1", "1Min").replace("5", "5Mins").replace("10", "10Mins").replace("15", "15Mins").replace("30", "30Mins").replace("60", "1Hr").replace("120", "2Hrs").replace("240", "4Hrs").replace("480", "8Hrs").replace("720", "12Hrs").replace("1440", "24Hrs");

If I try this, i get '1Min5Mins' because it replaces 1 and then 5.

This could be a stupid question, I can do it with switch or if, else-if. just wondering can this be done in 1 line code. Thanks

like image 730
Ana Avatar asked May 11 '26 18:05

Ana


2 Answers

You could try something like this:

String str = "15";
int minutes = Integer.parseInt(str);
if (minutes < 60)
    str += "Mins";
else
    str = (minutes/60) + "Hrs";

but be aware that Integer.parseInt() will throw an exception if you try to parse anthing else than a number. This can be inaccurate if the hours are not exact (365 will be replaced by 6 hours although it's 6 hours and 5 minutes)

Here's the 1-liner:

str = Integer.parseInt(str) < 60 ? str+"Mins" : (Integer.parseInt(str)/60) + (Integer.parseInt(str)/60 == 1 ? "Hr" : "Hrs");

although this would be more readable with a 2-liner:

int minutes = Integer.parseInt(str);
str = minutes < 60 ? str+"Mins" : (minutes/60) + (minutes/60 == 1 ? "Hr" : "Hrs");
like image 58
ParkerHalo Avatar answered May 14 '26 08:05

ParkerHalo


Here is the one-liner for you:

String newStr = str.replaceAll("\\b1\\b", "1Min").replaceAll("\\b5\\b", "5Mins").replace("10", "10Mins").replace("15", "15Mins").replace("30", "30Mins").replace("60", "1Hr").replace("120", "2Hrs").replace("240", "4Hrs").replace("480", "8Hrs").replace("720", "12Hrs").replace("1440", "24Hrs");

With the regex word boundaries. Was too lazy to finish it till the end.

like image 34
Murat Karagöz Avatar answered May 14 '26 06:05

Murat Karagöz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!