Replace portion of String

To replace specific portion of String, say we have String like Hello 1234! and we want to convert it to Hello 12World34! then we don’t have any direct way to go with String.

To achieve this with inbuilt classes of Java we have an option of StringBuilder. Kindly note that String also has methods like replace, replaceFirst etc. but these methods can not replace specific part of String from say index 5 to index 9. Consider following program to achieve this with StringBuilder.

public class ReplaceStringPortion {

	public static void main(String[] args) {
		String str = "Hello World!";
		StringBuilder sb = new StringBuilder(str);
		int start = 6, end = 10;
		sb.replace(start, end, "#REPLACE");
		System.out.println(sb);
	}
	
}

Above program will print Hello #REPLACEd! in console. Kindly note that you can use some third party library as well to tackle this problem.

To get start and end, you can also use String methods like String#indexOf or String#lasIndexOf.

Apart from that String also provide replaceAll method which takes regular expression as an argument and so in some cases this method may also do the trick.

Same way somehow, String#subString can also be used to achieve this but it will take more efforts than the StringBuilder way.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s