user6750519 user6750519 - 1 year ago 112
Java Question

Java list index out of range

In java, what is the best way to switch characters in a string while keeping the rest of the characters in their original spot. My real concern is if there's a way to deal with this index out of range error other than the following:
Let's say you want to switch the letter r with the capital E in "stringExample".

you can chunk this into "st" + "r" + "ing" + "E" + "xample"


then to switch "r" & "E": "st" + "E" + "ing" + "r" + "xample"


The only problem is if k is the last index then you need to write an if statement to catch this exception. Other than doing what I suggested before, is there a better way of switching these letters?

Answer Source

If you're looking to just replace characters in a string, you're probably best off rebuilding your string entirely using String.substring. For your example, you'd simply need to use temporary variables to hold the letters you want to swap. For example:

String swapLetters(String str, int firstIndex, int secondIndex) {
    if (firstIndex < 0 || firstIndex >= str.length()) {
        throw new IndexOutOfBoundsException("firstIndex '" + firstIndex + "' is out of bounds.");
    } else if (secondIndex < 0 || secondIndex >= str.length()) {
        throw new IndexOutOfBoundsException("secondIndex '" + secondIndex + "' is out of bounds.");
    } else if (firstIndex >= secondIndex) {
        throw new IndexOutOfBoundsException("firstIndex isn't before secondIndex");

    StringBuilder newString = new StringBuilder(str.substring(0, firstIndex));
    newString.append(str.charAt(secondIndex)).append(str.substring(firstIndex + 1, secondIndex))
             .append(str.charAt(firstIndex)).append(str.substring(secondIndex + 1));

    return newString.toString();

Here, even if it's the last letter the substring will just return an empty string and it'll be fine.

System.out.println("stringExample becomes " + swapLetters("stringExample", 2, 12)); //--> stringExample becomes steingExamplr
System.out.println("stringExample becomes " + swapLetters("stringExample", 2, 6)); //--> stringExample becomes stEingrxample

If you want to just replace the first instance of each letter given letters, you'd use indexOf('r') instead of charAt(2), for example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download