1

So i have a program where i want to replace specific characters in the program with other letters. However, when i run this program, it seems to keep reverting the changed characters back. This is the code so far:

  public static String changeSample(String sample) {

    for (int i = 0; i < sample.length(); i++) {

        if (sample.charAt(i) == 'A') {

            sample = sample.replace(sample.charAt(i), 'B');
            continue;

        }

        else if (sample.charAt(i) == 'B') {

            sample = sample.replace(sample.charAt(i), 'A');
            continue;

        }

    }

   return sample;

Is there a way that i can iterate through each character in the string and then check if it is either an A, B, C, D, E, or F and change it to its complimentary letter, i.e. A to B, B to A, C to D, D to C, E to F, F to E.

7
  • That's only part of your method. Please show us the rest, as I suspect the issue is a simple misunderstanding about how objects and references work. Commented May 29, 2016 at 10:25
  • Is your code being compiled ?? you missed i++ or i=i+1 ? Commented May 29, 2016 at 10:25
  • 1
    @ShreeKrishna: He didn't miss it, it's inside the if statements. However, he'll have an endless loop if the character isn't handled. Commented May 29, 2016 at 10:29
  • 1
    Are you returning a new String with the altered content? I don't see a return statement. In the current form, the method won't compile, since it needs to return a String. Commented May 29, 2016 at 10:30
  • 2
    Its the problem of replace method that it will replace all occurrences of character in the string. Commented May 29, 2016 at 10:32

1 Answer 1

4

replace() will return a new String where ALL occurrences of a particular character are changed, not just a character at a particular position. So your problem is that the repeated replace() statements are effectively modifying the values back and forth.

Because a String is immutable, you cannot simply replace its characters with others dynamically. So, convert your code to use a StringBuilder instead.

StringBuilder buildSample = new StringBuilder();
buildSample.append(sample);

Now you can use setCharAt() instead of replace() to change the character at one position at a time.

buildSample.setCharAt(i, 'A');

At the end, you can return buildSample.toString().

As for changing each letter A to F to its complement, if only these six letters are required, a hard-coded function with a switch statement would do. Otherwise you can use a function like complementaryLetter() below, which returns the complement after checking the ASCII value of the character. This will work for all characters. You can add code to handle invalid cases, for non-character input.

A complete working code:

public class Replace {
    public static void main(String[] args) {
        String s1 = "ABCDEFA";
        System.out.println(s1);
        s1 = changeSample(s1);
        System.out.println(s1);
    }

    public static char complementaryLetter(char letter) {
        char retChar = 'A';
        if ((int) letter % 2 == 0)
            retChar = (char) ((int)letter - 1);
        else
            retChar = (char) ((int) letter + 1);
        return retChar;
    }

    public static String changeSample(String sample) {
        StringBuilder buildSample = new StringBuilder();
        buildSample.append(sample);
        for (int i = 0; i < sample.length(); i++) {
            buildSample.setCharAt(i, complementaryLetter(sample.charAt(i)));
        }
        return buildSample.toString();
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Though your answer is correct but I doubt correctness of your explanation. You said that Because a String is immutable, you cannot simply replace one character at a time , can you please explain a little more ? As I know, String being immutable can't be modified and it doesn't really care about if a single character is modified or multiple.
Yes, a String cannot be modified at all. I was giving a more specific response to his requirement of changing characters, saying it cannot be done like that.
I edited my answer to remove that ambiguity, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.