8
String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i++;", "");

// Desired output :: newCode = "helloworld";

But this is not replacing i++ with blank.

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Android Guy
  • 573
  • 1
  • 8
  • 18

3 Answers3

8

just use replace() instead of replaceAll()

String preCode = "helloi++;world";
String newCode = preCode.replace("i++;", "");

or if you want replaceAll(), apply following regex

String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i\\+\\+;", "");

Note : in the case of replace() the first argument is a character sequence, but in the case of replaceAll the first argument is regex

Navneet Krishna
  • 5,009
  • 5
  • 25
  • 44
  • "this is helpfull if you have multiple occurances of character to be replaced" - The only difference between the two function is that one uses regex and the other uses string literals. Both their description starts with "Replaces each substring of this string that matches..." – Simon Kraemer Aug 06 '18 at 12:20
  • `java.util.regex.Pattern.quote(java.lang.String)` will prevent you from making mistakes when converting a string literal to a regex. – Simon Kraemer Aug 06 '18 at 12:21
  • thanks for the suggestion, i have updated the answer now – Navneet Krishna Aug 06 '18 at 12:24
3

try this one

 public class Practice {
 public static void main(String...args) {
 String preCode = "Helloi++;world";
 String newCode = preCode.replace(String.valueOf("i++;"),"");
 System.out.println(newCode);
}  
}
2

The problem is the string that you are using to replace , that is cnsidered as regex pattern to skip the meaning you will have to use escape sequence like below.

String newCode = preCode.replaceAll("i\\+\\+;", "");