studentneedshelp
studentneedshelp

Reputation: 9

Read a string and 2 index variables then swap those characters in specified index

My program needs to read a string and two index values from the user, then swap the characters with the specified index values, and save the resulting string in a variable. Right now all i can do is swap the 2 first letters of the user input string and i am unable to figure out how to swap 2 index values from the user

Upvotes: 0

Views: 556

Answers (2)

Adrian Sohn
Adrian Sohn

Reputation: 1271

You could swap the characters like this assuming you have the original String and the two indices.

public static String swapChars(String word, int firstIndex, int secondIndex) {
    if (Math.min(firstIndex, secondIndex) < 0 || Math.max(firstIndex, secondIndex) > word.length() - 1) { // If either of the indices are negative or too large, throw an exception
        throw new IllegalArgumentException("Indices out of bounds!");
    }
    if (firstIndex == secondIndex) { // If they are equal we can return the original string/word
        return word;
    }
    char[] characters = word.toCharArray(); // Make a char array from the string
    char first = characters[firstIndex]; // Store the character at the first index
    characters[firstIndex] = characters[secondIndex]; // Change the character at the first index
    characters[secondIndex] = first;  // Change the character at the second index using the stored character
    return new String(characters); // Return a newly built string with the char array
}

Upvotes: 0

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

Use String.toCharArray() to convert the input to a char[]. Then you can work with the indices and swap the required characters. Then all you need is to construct a new string from the array. Refer to the String javadocs.

Upvotes: 1

Related Questions