Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a String from another String?

Tags:

java

string

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.

like image 989
vijayk Avatar asked Jan 22 '26 09:01

vijayk


2 Answers

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("="));
like image 147
Maroun Avatar answered Jan 24 '26 03:01

Maroun


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("="));
like image 34
Rohit Jain Avatar answered Jan 24 '26 02:01

Rohit Jain