2

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.

4 Answers 4

5

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("="));
Sign up to request clarification or add additional context in comments.

Comments

4

First of all, since Strings 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("="));

Comments

4

what all you need to do is

String a=path.substring(0, path.lastIndexOf("="));

Comments

0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.