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.
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("="));
你需要做的就是
String a=path.substring(0, path.lastIndexOf("="));
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("="));
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.