Spread the love

Replacing characters in a common task in programming language. For example, you may want to replace every instance of a particular letter with a different one.

How to Replace Characters in a String Using Java

1. Method Signature

We’ll start by defining a method that handles the replacement. Here’s the method signature:

public static String repl(String S, char c1, char c2)

Parameters:

  • String S: The string where we want to replace characters.
  • char c1: The character to be replaced.
  • char c2: The replacement character.

The method returns the modified string after replacements.

2. Initializing a New String

Next, we initialize an empty string S1 to build our result:

String S1 = "";

This string will hold the final output after processing the input string.

3. Looping Through the Original String

We then loop through each character of the original string to check if it matches the character we want to replace:

for (int i = 0; i < S.length(); i++) {
    char s1 = S.charAt(i);
}

Here, we’re iterating over the string S and extracting each character using S.charAt(i).

4. Condition to Replace Characters

Inside the loop, we use an if-else statement to check whether the current character matches c1:

if (s1 == c1) {
    s1 = c2;
    S1 += s1;
} else {
    S1 += s1;
}

If s1 matches c1, we replace it with c2 and append it to S1. Otherwise, we simply append the original character.

5. Returning the Final Result

After the loop completes, we return the modified string S1:

return S1;

6. Full Method Code

Here’s the complete method implementation:

public static String repl(String S, char c1, char c2) {
    String S1 = "";
    for (int i = 0; i < S.length(); i++) {
        char s1 = S.charAt(i);
        if (s1 == c1) {
            s1 = c2;
            S1 += s1;
        } else {
            S1 += s1;
        }
    }
    return S1;
}

7. Example Execution in the main Method

We can test the repl method by calling it inside the main method:

public static void main(String[] args) {
    System.out.println(repl("Hello", 'l', 'x'));
}

The expected output when running this program is:

Hexxo

Leave a Reply

Your email address will not be published. Required fields are marked *