Articles
Java Program to replace a substring without using replace method
Given a string str that may consist a sequence of characters and we need to replace a sub-string with a specific character sequence without using replace method.
Program:
class Main {
public static void main(String[] args) {
String str = "newBay", replace="new";
String replaceTo = "programmer";
int position =str.indexOf(replace);
int len = replace.length();
String new_string = str.substring(0, position) + replaceTo +
str.substring(position+len);
System.out.println(new_string);
}
}
Output:
ProgrammerBay
Explanation
- Have a string str containing ‘newBay’
- In the above code, we need to replace substring ‘new’ present in ‘newBay’ with ‘programmer’
- Storing the occurring position of ‘replace’ string and its length too
- Since, the position of ‘new’, we got is 0 , therefore, str.substring(0,position) would extract nothing
- replaceTo concatenated with ‘ ‘ subtring extracted by str.substring(0,position)
- str.substring(position+len) extracted ‘Bay’ from ‘newBay’. Now after concatenating, we got ‘ProgrammerBay’
This post was last modified on June 18, 2020
Tags: java program replace string substring without using replace method