Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract String from String

Tags:

java

string

I have a string 1.2 sec or say 0.4 sec What I am trying to do is simple, just remove sec from the end of the string. I want to do it in just one line. I know the other ways, convert to char array search for space and delete and all after that but I was wondering if this could be done like "1.2 sec" - " sec" or like time - " sec" or something like that but just in a line or two. If there isn't then I know how to do it. But if there is how?

Update:

If I execute this code:

String time = stopwatch1.getjLabel4text();
String replace = time.replace(" sec","");
System.out.println(replace+"");
System.out.println(time+"");

I get output:

2.0 Sec
2.0 Sec
like image 927
Daksh Shah Avatar asked Oct 15 '25 02:10

Daksh Shah


2 Answers

Say the string is stored in s, you could use s.replaceAll(" Sec","") to remove it.

like image 176
anirudh Avatar answered Oct 17 '25 16:10

anirudh


You can do

    String str = "1.2 sec";
    String requiredString = str.substring(0,str.indexOf('s')).trim();
like image 27
Aniket Thakur Avatar answered Oct 17 '25 16:10

Aniket Thakur



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!