Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace slash with underscore [duplicate]

Tags:

java

Possible Duplicate:
Hints for java.lang.String.replace problem?
Using string.replace() in Java

Why "/" does not replaced by "_" ?

public static void main(String[] args) throws IOException {
    String file = "A/B";
    file.replaceAll("/", "_");
    System.out.println(file);
}
like image 607
Mehdi Avatar asked Jul 30 '26 20:07

Mehdi


2 Answers

Because instances of java.lang.String are immutable*. replaceAll returns the correct string, but your program throws it away. Change your program as follows to correct the issue:

file = file.replaceAll("/", "_");


* That's a fancy way of saying "non-changeable": once a string instance "A/B" is created, there are no methods that you could call on it to change that value.
like image 128
Sergey Kalinichenko Avatar answered Aug 01 '26 11:08

Sergey Kalinichenko


You need to store the result of the file.replaceAll() call as String instances are immutable:

file = file.replaceAll("/", "_");
like image 21
hmjd Avatar answered Aug 01 '26 10:08

hmjd



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!