MisterIbbs
MisterIbbs

Reputation: 257

How to replace part of a String in Java?

Im trying to replace part of a String based on a certain phrase being present within it. Consider the string "Hello my Dg6Us9k. I am alive.".

I want to search for the phase "my" and remove 8 characters to the right, which removes the hash code. This gives the string "Hello. I am alive." How can i do this in Java?

Upvotes: 1

Views: 8241

Answers (5)

CeeEll
CeeEll

Reputation: 1

If you want to be flexible about the hash code length, use the folowing regexp:

String foo="Hello my Dg6Us9k. I am alive.";
String bar = foo.replaceFirst("\\smy.*?\\.", ".");
System.out.println(bar);

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

Use regex like this :

public static void main(String[] args) {
    String s = "Hello my Dg6Us9k. I am alive";
    String newString=s.replaceFirst("\\smy\\s\\w{7}", "");
    System.out.println(newString);
}

O/P : Hello. I am alive

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174836

You could achieve this through string.replaceAll function.

string.replaceAll("\\bmy.{8}", "");

Add \\b if necessary. \\b called word boundary which matches between a word character and a non-word character. .{8} matches exactly the following 8 characters.

To remove also the space before my

System.out.println("Hello my Dg6Us9k. I am alive.".replaceAll("\\smy.{8}", ""));

Upvotes: 5

qznc
qznc

Reputation: 1173

Java strings are immutable, so you cannot change the string. You have to create a new string. So, find the index i of "my". Then concatenate the substring before (0...i) and after (i+8...).

int i = s.indexOf("my");
if (i == -1) { /* no "my" in there! */ }
string ret = s.substring(0,i);
ret.concat(s.substring(i+2+8));
return ret;

Upvotes: 1

Jens
Jens

Reputation: 69495

This should do it:

String s = ("Hello my Dg6Us9k. I am alive");
s.replace(s.substring(s.indexOf("my"), s.indexOf("my")+11),"");

That is replacing the string starts at "my" and is 11 char long with nothing.

Upvotes: 2

Related Questions