To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.
To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.
Try below code. With help of StringBuffer you do replacement. StringBuffer replace java docs
public static void main(String[] args) {
StringBuffer buf = new StringBuffer("123456789");
int start = 3;
int end = 6;
buf.replace(start, end, "foobar");
System.out.println(buf);
}
}
After running above program below will be out put.
123foobar789
Demo
Firstly, you cannot do it1, since a String
is immutable in java.
However, you can create a new String object with the desired value, using the String#substring()
method (for example):
String s = "123456789";
String newString = s.substring(0, 3) + "foobar" + s.substring(3+3);
System.out.println(newString);
If you do want to achieve it efficiently, you could avoid creating some intermediate strings used by the concatinating and substring()
method.
String s = "123456789";
StringBuilder sb = new StringBuilder();
char[] buff = s.toCharArray();
sb.append(buff , 0, 3).append("foobar");
sb.append(buff,3+3,buff.length -(3+3));
System.out.println(sb.toString());
However, if it is not done in a very tight loop - you should probably ignore it, and stick with the first and more readable solution.
(1) not easily anyway, it can be done with reflection - but it should be avoided.
If there is no repetition of given substring then try this.
String s ="123456789";
s = s.replace(s.substring(3,6), "foobar");
If there is repetition of given substring then try this.
String s ="123123123";
s= s.substring(0,3) + "foobar" + s.substring(6,s.length());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With