How would I swap 2 letters in a java string using toCharArray()?

Viewed 129

I want ab to be returned as ba but my output is a a. I understand why I get that output. If a[i] < a[j] (if 1st index < 2nd index, which is true because a < b, then replace b (a[j]) with a (a[i])).

I just can't wrap my head around how I would go about swapping those two letters with arrays.

How would I be able to accomplish this?

public static void solution(String A) {
    char[] a = A.toCharArray();

    for(int i = 0; i < a.length; i++) {
        for(int j = i + 1; j < a.length; j++) {
            if(a[i] < a[j]) {
                a[j] = a[i];
            }
        }
    }

    for(int i = 0; i < a.length; i++) {
        System.out.print(a[i] + " ");
    }
}

public static void main(String args[]) {
    String A = "ab";

    solution(A);
}
2 Answers

You could use a temporary variable and place a[j] in it, then override a[j] with a[i] and finally override a[i] with the old value of a[j] you stored in the temporary variable:

if (a[i] < a[j]) {
    char temp = a[j];
    a[j] = a[i];
    a[i] = temp;
}

you really want to create a temp to store your character, BUT if you're trying to write less code and don't care about performance, you can even just reverse the string in your case, instead of using toCharArray, using java's StringBuilder package

    import java.lang.*;

    StringBuilder input = new StringBuilder;
    input.append(A);
    input = input.reverse();
    System.out.print(input);
Related