How to put the value of an array in another?

String input = txtInput.getText();

char[] charArray =  input.toCharArray();
char[] flipArray = null;
System.out.println(charArray.length);
for (int i = 0; i < charArray.length ; i++) {
    System.out.println(charArray[i]);

Sorry if the code doesn't make sense.

charArray is taken from JTextField.

Therefore, the code should do something like this.

  • Receives a message and flips every 2 characters. That is, the 1st and 2nd characters switch, and the 3rd and 4th switches, etc.
  • For example, "You cannot read my message!" after encryption will be "oY uac'n terdam yemssga! e";

charArray is a message that says: "You cannot read my message!" flipArray will carry a message that says "oY uac'n terdam yemssga! e"

How to write a loop that puts it in such a way that ...

charArray[0] = flipArray[1]
charArray[1] = flipArray[0]
charArray[2] = flipArray[3]
charArray[3] = flipArray[2]
charArray[4] = flipArray[5]
charArray[5] = flipArray[4]

The value of charArray is taken from JTextField.

I do this in NetBeans IDE 6.5.1.

+2
3

.

for( int i = 0; i < charArray.length; i+= 2 )
{
   charArray[i] = flipArray[i+1];
   charArray[i+1] = flipArray[i];
}

, 0,1 1,0, 2,3 3,2 ..

, , :

String input = ...
StringBuilder builder = new StringBuilder();

for( int i = 0; i < input.length(); i += 2 )
{
   //guard against odd text lengths
   if( i+1 < input.length() )
   {
      builder.append( input.charAt(i+1) );
   }   
   builder.append( input.charAt(i) );
}

String flippedText = builder.toString();
+2

, :

System.out.println(
   "012345".replaceAll("(.)(.)", "$2$1")
);
// "103254"

, String s, s.replaceAll("(.)(.)", "$2$1")) , s . s , . , (?s) embedded Pattern.DOTALL.

.. (.. " " ), . , .

  MATCH: (.)(.)
          1  2
 REPLACE
   WITH:  $2$1

Java regex, . $1 , .


:

    System.out.println(
       "abcdefg".replaceAll("(.)(.)", "$1[$2]")
    );
    // "a[b]c[d]e[f]g"

    System.out.println(
       "> Regular expressions: now you have two problems!"
          .replaceAll("(.)(.)", "$2$1")
    );
    // " >eRugal rxerpseisno:sn woy uoh va ewt orpboelsm!"

    System.out.println(
       "> Regular expressions: now you have two problems!"
          .replaceAll("(\\w)(\\w)", "$2$1")
    );
    // "> eRugalr xerpseisnos: onw oyu ahev wto rpboelsm!"

    System.out.println(
       "Wow! Really?? That awesome!!!"
          .replaceAll("(.)([!?]+)", "$1$1$1$2$2")
    );
    // "Wowww!! Reallyyy???? That awesomeee!!!!!!"
+3
char[] flipArray = new char[charArray.length];
...
    charArray[i] = flipArray[i^1];

, .

^ .

-twiddling:

    charArray[i] = flipArray[(i/2)*2 + 1-(i%2)];

% ( ).

, , NIO, .

+2
source

All Articles