Swap multiple characters in a string in java?

I need to process a string to replace multiple characters for simple encryption.

 Input : ABCDEFGHIJKLMNOPQRSTUVWXYZ
 Output: NOPQRSTUVWXYZABCDEFGHIJKLM

      

In the above process, I split the string into two and moved the first half to the last half.

final int mid = (xyz.length()+1) / 2;
String[] spstr = {
    xyz.substring(0, mid),
    xyz.substring(mid),
};
String firstMix=spstr[1]+spstr[0];
System.out.println(firstMix);

      

Now I need to swap the first two characters with the last two characters

Input : NOPQRSTUVWXYZABCDEFGHIJKLM
Output: LMPQRSTUVWXYZABCDEFGHIJKNO

      

and also swap two characters at once to the left of the middle of the line with two characters that immediately follow them.

Input :  LMPQRSTUVWXYZABCDEFGHIJKNO
Output : LMPQRSTUVWXABYZCDEFGHIJKNO

      

Swap occupies space between "YZAB" and "ABYZ" in terms of input and output

What would be the best way to effectively change these characters? In this process, I will convert many strings. The string length in this case is not constant.

+3


source to share


4 answers


This is mostly correct, except in the case of undefined to replace the middle characters with the length of the string, which is odd. Comments should be sufficient for understanding the code.

public class Main {

    public static void main( String[] args ) {

        char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

        final int mid = ( chars.length + 1 ) / 2;


        System.out.println( "Mid: " + mid );
        System.out.println( "Start : " + new String( chars ) );

        // Pass one : Swap first half chars with last half chars
        if( ( chars.length % 2 ) == 1 ) {
            /* We swap the characters this way because the left half
             *  is one character longer than the right half. To avoid
             *  unnecessary copies we move the right character to
             *  the index before the left character and save the first
             *  character to be placed at the mid point
             */
            char first = chars[ 0 ];
            for( int l = 1, r = mid; r < chars.length; l++, r++ ) {
                chars[ l - 1 ] = chars[ r ];
                chars[ r ] = chars[ l ];
            }
            chars[ mid - 1 ] = first;
        }
        else {
            for( int l = 0, r = mid; r < chars.length; l++, r++ ) {
                swap( chars, l, r );
            }
        }

        System.out.println( "Pass 1: " + new String( chars ) );

        // Pass two: Swap first two chars with last two chars
        swap( chars, 0, chars.length - 2 );
        swap( chars, 1, chars.length - 1 );

        System.out.println( "Pass 2: " + new String( chars ) );

        // Pass three: Swap middle 4 characters.
        swap( chars, mid - 1, mid + 1 );
        swap( chars, mid - 2, mid );

        System.out.println( "Pass 3: " + new String( chars ) );
    }


    public static void swap( char[] chars, int l, int r ) {
        char tmp = chars[ l ];
        chars[ l ] = chars[ r ];
        chars[ r ] = tmp;
    }
}

      



I decided to do some manipulation with character arrays to reduce the number of objects created. This, in my opinion, is the fastest solution for what you are asking. When / if you clarify the undefined case, I can edit the code to provide correct output.

+1


source


I would just create a method, convert strings to arrays, and use their index to manipulate and encrypt characters.



+3


source


You might want to try using the StringBuilder class. It provides many useful methods for manipulating strings, but avoids the problem of creating a lot of String objects in the process.

+2


source


JAVACODE

The best way is to split the string into an array of strings and do as below as per your requirement

http://www.compileonline.com/compile_java_online.php For code testing

import java.util.Arrays;
        public class HelloWorld{

             public static void main(String []args){

                System.out.println("Hello World");

                String xyz= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                final int mid = (xyz.length()+1) / 2;

                String[] spstr = {
                    xyz.substring(0, mid),
                    xyz.substring(mid)
                };

                String firstMix=spstr[1]+spstr[0];

                String[] array = firstMix.split("");


                //Swap first and last two characters
                for(int i=1;i<3;i++)
                {
                   String temp= array[i];

                   array[i]=array[array.length-i];
                    array[array.length-i]=temp;

                }    



                String str1 = Arrays.toString(array); 
                str1 = str1.substring(1, str1.length()-1).replaceAll(",", "");

                //Swap  two characters left of middle with right of middle
                int  j=2;
                 for(int i=((array.length/2)-2);i<(array.length)/2;i++)
                {
                   String temp= array[i];
                   array[i]=array[array.length/2+j];
                   array[array.length/2+j]=temp;
                   j--;
                }   
                 String str2 = Arrays.toString(array); 
                  str2 = str2.substring(1, str2.length()-1).replaceAll(",", "");
                    System.out.println( firstMix);
                 System.out.println(str1);
                   System.out.println(str2);

             }
        }

      

+1


source







All Articles