without using replace method – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Thu, 18 Jun 2020 12:22:01 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg without using replace method – Programmerbay https://programmerbay.com 32 32 Java Program to replace a substring without using replace method https://programmerbay.com/java-program-to-replace-a-substring-without-using-replace-method/ https://programmerbay.com/java-program-to-replace-a-substring-without-using-replace-method/#respond Thu, 27 Feb 2020 04:53:26 +0000 https://programmerbay.com/?p=6125 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’

]]>
https://programmerbay.com/java-program-to-replace-a-substring-without-using-replace-method/feed/ 0