How to swap String characters in Java?

后端 未结 14 2248
佛祖请我去吃肉
佛祖请我去吃肉 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: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();
    }
    

提交回复
热议问题