Replace Character in a String in Java without using replace() method

Java 8Object Oriented ProgrammingProgramming

To replace a character in a String, without using the replace() method, try the below logic.

Let’s say the following is our string.

String str = "The Haunting of Hill House!";

To replace character at a position with another character, use the substring() method login. Here, we are replacing 7th position with character ‘p’

int pos = 7;
char rep = 'p';
String res = str.substring(0, pos) + rep + str.substring(pos + 1);

The following is the complete example wherein a character at position 7 is replaced.

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       String str = "The Haunting of Hill House!";
       System.out.println("String: "+str);
       // replacing character at position 7
       int pos = 7;
       char rep = 'p';
       String res = str.substring(0, pos) + rep + str.substring(pos + 1);
       System.out.println("String after replacing a character: "+res);
    }
}

Output

String: The Haunting of Hill House!
String after replacing a character: The Haupting of Hill House!
raja
Published on 12-Dec-2018 07:28:55
Advertisements