Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Syntax
1.2.
Parameters of the method
1.3.
Return Value
1.4.
Implementation
1.5.
Example-1
1.6.
Example-2
2.
Frequently Asked Questions
2.1.
What are methods in java?
2.2.
What are parameters in the method?
2.3.
What is the time-complexity of the operation of the replace method?
3.
Conclusion
Last Updated: Mar 27, 2024
Easy

String replace( )

Author Ankit kumar
1 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

The replace method in java is used to replace all the occurrences of a char with the given character. It first searches the String for a specified character and then returns a new string where the specified character(s) are replaced with the given one.

String replace()

Syntax

public String replace(char oldChar, char newChar)

Parameters of the method

  1. Old Character
  2. New Character
  3. Target String

Return Value

New String (Replaced)

Implementation

public String replace(char oldChar, char newChar) {    
      if (oldChar != newChar) {    
          int len = value.length;    
          int i = -1;    
          char[] val = value;    
    
          while (++i < len) {    
              if (val[i] == oldChar) {    
                  break;    
              }    
          }    
          if (i < len) {    
              char buf[] = new char[len];    
              for (int j = 0; j < i; j++) {    
                  buf[j] = val[j];    
              }    
              while (i < len) {    
                  char c = val[i];    
                  buf[i] = (c == oldChar) ? newChar : c;    
                  i++;    
              }    
              return new String(buf, true);    
          }    
      }    
      return this;    
  }    
public String replace(CharSequence target, CharSequence replacement)  
{         
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(  
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));  
}

 

Example-1

public class Example1 {  
    public static void main(String[] args) {  
        String str = "IloveCodingNinjas";  
        String res = str.replace("i","e"); // Replace 'i' with 'e'  
        System.out.println(res);  
        res = rs.replace("e","i"); // Replace 'e' with 'i'  
        System.out.println(res);  
    }  
}

 

Output

IloveCodengNenjas
IloveCodingNinjas

 

Explanation: Since we are calling the replace method on string str with oldChar = ‘i’ and newChar = ‘e’, therefore we got the first output .In the second call, we again called replace but this time with reversed parameters, therefore we got our original string.

Example-2

public class Example2{  
    public static void main(String args[]){  
        String s1="I Love Coding Ninjas I love Coding Ninjas";  
        String modifiedString=s1.replace("I","U");//replaces all occurrences of "I" to "U"  
        System.out.println(modifiedString);  
    }
} 

 

Output

U Love Coding Ninjas U Love Coding Ninjas

 

Explanation: In the example above, replace method is called for string s1 with oldChar = ‘I’ and newChar = ‘U’, therefore we got our output with all the oldChar replaced with newChar ‘U’.

Frequently Asked Questions

What are methods in java?

Methods are the block of code that runs when they are called. In order to invoke a method, one needs to pass the parameter into it. They are called to perform specific tasks.

What are parameters in the method?

Parameters can be defined as the information that can be passed to the method. When passed, they act as variables inside the method.

What is the time-complexity of the operation of the replace method?

The time-complexity of the operation of the replace method would be of order O(n). Since searching can cost a linear time thus leads to O(n) complexity.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Conclusion

In this article, we discussed the String replace method of java, its syntax, parameters, implementation, and finally, some examples.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available, interview puzzles, take a look at the interview experiences, and interview bundle for placement preparations.

We hope that this blog has helped you enhance your knowledge regarding puzzles, and if you liked this blog, check other links.

Do upvote our blog to help other ninjas grow.

Happy Coding!"

Live masterclass