-5

I have one issue regarding string parsing.

String str = "jdaskks sms=<hello
hi wini>";

Here u can see, the new line character present in string. I have written a program, which searches for sms= string , then gets substring from < > character. in which i check for new line character and replace it with ' '.

But i have issue, when i get substring . i replace it. but how to change this in original string str, as i can see change in substring not in original string.

Help is appreciated.

str.substring(j,str.indexOf('>',j+1)).replaceAll("\n", "#10");
here j is index of '<'

If i assign this string, i will get the substring with replace char, not original string with replaced new line character

Wini
  • 25
  • 1
  • 7

3 Answers3

3

Strings are immutable in Java - operations like replace don't actually update the original string. You have to use the return value of the substring call, e.g.

String updated = str.substring(j,str.indexOf('>',j+1)).replaceAll("\n", "#10");

If you want to replace this in the overall string, you can simply concatenate this back into the string:

int indexOf = str.indexOf('>',j+1);
str = str.substring(0, j)
    + str.substring(j,indexOf).replaceAll("\n", "#10"))
    + str.substring(indexOf);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

You are able to get the substring but you are not assigning it to a string or using for displaying.Because strings are immutable.

So just assign result to a new string:

String result= str.substring(j,str.indexOf('>',j+1)).replaceAll("\n", "#10");

or use it for displaying.

System.Out.Println(str.substring(j,str.indexOf('>',j+1)).replaceAll("\n", "#10"));
VVN
  • 1,607
  • 2
  • 16
  • 25
0

As you have created a new String object but didn't assign it back to a variable, is the cause of you issue.

Rishi
  • 1,163
  • 7
  • 12