Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does String.replace not work? [duplicate]

I am a little bit confused at the moment. I tried that:

String test = "KP 175.105"; test.replace("KP", ""); System.out.println(test); 

and got:

KP 175.105 

However, I want:

175.105 

What's wrong with my code?

like image 720
maximus Avatar asked Mar 16 '13 14:03

maximus


People also ask

Why replace is not working in Javascript?

The "replace is not a function" error occurs when we call the replace() method on a value that is not of type string . To solve the error, convert the value to a string using the toString() method before calling the replace() method.

Does string replace replacing all occurrences?

The String type provides you with the replace() and replaceAll() methods that allow you to replace all occurrences of a substring in a string and return the new version of the string.

Can we use Replace method in string?

Java String replace() MethodThe replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.

Is string replace inplace in Java?

Thank you in advance!!! It might be a trick question; Java strings are immutable so you can't change them "in place".


1 Answers

You did not assign it to test. Strings are immutable.

test = test.replace("KP", ""); 

You need to assign it back to test.

like image 155
PSR Avatar answered Oct 16 '22 03:10

PSR