Reputation: 2753
I want to remove some String from my original path, but I cant replace the another string from my original String
This is my code
String path="contentPath =C/Users/consultant.swapnilb/Desktop/swapnil=Z:/Build6.0/Digischool/";
String a=path.substring(path.lastIndexOf("="), path.length());
path.replace(a, "");
System.out.println("a---"+a);
System.out.println("path---"+path);
I just want to remove =Z:/Build6.0/Digischool/
from my original path.
Upvotes: 2
Views: 176
Reputation: 492
String is a immutable class(Due to security reasons) you can not assign any other value to it once it is initialized. You have to assign the substring to some other string object and then access it. Just change your code as shown below it will work.
String path="contentPath =C/Users/consultant.swapnilb/Desktop/swapnil=Z:/Build6.0/Digischool/";
String a=path.substring(path.lastIndexOf("="), path.length());
String b = path.replace(a, "");
System.out.println("a---"+a);
System.out.println("path---"+path);
System.out.println(b);
Upvotes: 0
Reputation: 213203
First of all, since String
s are immutable in Java, you have to re-assign the changes in a String
to another reference:
path = path.replace(a, "");
Secondly, you are doing extra job out there. You can replace these lines:
String a=path.substring(path.lastIndexOf("="), path.length());
path.replace(a, "");
with:
path = path.substring(0, path.lastIndexOf("="));
Upvotes: 4
Reputation: 8657
what all you need to do is
String a=path.substring(0, path.lastIndexOf("="));
Upvotes: 4
Reputation: 95948
See String#replace
:
public String replace(CharSequence target, CharSequence replacement)
↑
It returns a new object of type String
, you should assign the result:
path = path.replace(a, "");
However, you can simply do:
path = path.substring(0, path.lastIndexOf("="));
Upvotes: 5