How to swap String characters in Java?

后端 未结 14 2209
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 14:22

How can I swap two characters in a String? For example, \"abcde\" will become \"bacde\".

相关标签:
14条回答
  • 2020-12-08 14:46

    'In' a string, you cant. Strings are immutable. You can easily create a second string with:

     String second = first.replaceFirst("(.)(.)", "$2$1");
    
    0 讨论(0)
  • 2020-12-08 14:52

    Since String objects are immutable, going to a char[] via toCharArray, swapping the characters, then making a new String from char[] via the String(char[]) constructor would work.

    The following example swaps the first and second characters:

    String originalString = "abcde";
    
    char[] c = originalString.toCharArray();
    
    // Replace with a "swap" function, if desired:
    char temp = c[0];
    c[0] = c[1];
    c[1] = temp;
    
    String swappedString = new String(c);
    
    System.out.println(originalString);
    System.out.println(swappedString);
    

    Result:

    abcde
    bacde
    
    0 讨论(0)
  • 2020-12-08 14:52
    StringBuilder sb = new StringBuilder("abcde");
        sb.setCharAt(0, 'b');
        sb.setCharAt(1, 'a');
        String newString = sb.toString();
    
    0 讨论(0)
  • 2020-12-08 14:53

    Here's a solution with a StringBuilder. It supports padding resulting strings with uneven string length with a padding character. As you've guessed this method is made for hexadecimal-nibble-swapping.

    /**
     * Swaps every character at position i with the character at position i + 1 in the given
     * string.
     */
    public static String swapCharacters(final String value, final boolean padding)
    {
       if ( value == null )
       {
          return null;
       }
    
       final StringBuilder stringBuilder = new StringBuilder();
       int posA = 0;
       int posB = 1;
       final char padChar = 'F';
    
       // swap characters
       while ( posA < value.length() && posB < value.length() )
       {
          stringBuilder.append( value.charAt( posB ) ).append( value.charAt( posA ) );
          posA += 2;
          posB += 2;
       }
    
       // if resulting string is still smaller than original string we missed the last
       // character
       if ( stringBuilder.length() < value.length() )
       {
          stringBuilder.append( value.charAt( posA ) );
       }
    
       // add the padding character for uneven strings
       if ( padding && value.length() % 2 != 0 )
       {
          stringBuilder.append( padChar );
       }
    
       return stringBuilder.toString();
    }
    
    0 讨论(0)
  • 2020-12-08 14:53

    //this is a very basic way of how to order a string alpha-wise, this does not use anything fancy and is great for school use

    package string_sorter;

    public class String_Sorter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    
        String word = "jihgfedcba";
        for (int endOfString = word.length(); endOfString > 0; endOfString--) {
    
            int largestWord = word.charAt(0);
            int location = 0;
            for (int index = 0; index < endOfString; index++) {
    
                if (word.charAt(index) > largestWord) {
    
                    largestWord = word.charAt(index);
                    location = index;
                }
            }
    
            if (location < endOfString - 1) {
    
                String newString = word.substring(0, location) + word.charAt(endOfString - 1) + word.substring(location + 1, endOfString - 1) + word.charAt(location);
                word = newString;
            }
            System.out.println(word);
        }
    
        System.out.println(word);
    }
    

    }

    0 讨论(0)
  • 2020-12-08 14:53

    The following line of code will swap the first two characters in str:

    return str.charAt(1) + str.charAt(0) + str.substring(2);
    
    0 讨论(0)
提交回复
热议问题