Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

public static String swapEnds(String a) // return the string a with the first and last…

  1. User

    public static String swapEnds(String a) // return the string a with the first and last letters swapped // "pickles" -> "sicklep" // "bird" -> "dirb" // "regrets" -> "segretr"

  2. Assistant

    Here's the implementation of the swapEnds method:

    public static String swapEnds(String a) {
        // Check if the string has at least 2 characters
        if (a.length() < 2) {
            return a; // Return the original string as is
        }
        
        // Get the first and last characters of the string
        char first = a.charAt(0);
        char last = a.charAt(a.length() - 1);
        
        // Replace the first and last characters in the string
        String swapped = last + a.substring(1, a.length() - 1) + first;
        
        return swapped;
    }