在替换密码中保留空格和标点符号 Java

Keeping Spaces and Punctuation in Substitution Cipher Java

这个替换密码应该打乱字母表并通过找到消息中字母在正常字母表中的位置并将其替换为打乱字母表中相同位置的字母来对消息进行编码。

所以像 "ABC" 这样的消息,使用像 "QWERTYUIOPASDFGHJKLZXCVBNM" 这样的乱序字母将变成 "QWE"。

我的问题是标点符号和空格被其他字母替换,每个字母实际上并不对应于它的实际位置,它总是在它应该在的地方之后的一个地方。第二部分有点费解,但问题不大。

这是我的代码:

public static String cryptocodeM(String msg) {

    String[] alphabetArray = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    String newMsg = "";

    List<String> list = Arrays.asList(alphabetArray);
    Collections.shuffle(list);
    StringBuffer alph2 = new StringBuffer();

    for (int i = 1; i < list.size(); i++) {
        alph2.append(list.get(i));
    }

    String scramb = alph2.toString(); //the scrambled alphabet

    System.out.println(scramb);

    msg = msg.toUpperCase();

    for (int x = 0; x < msg.length(); x++) {
        char a = msg.charAt(x);  // the letters in msg

        int index = alphabet.indexOf(a) + 1; // index of the letters in the alphabet //when I don't add 1 here I get a runtime error saying "String out of range -1"  

        char b = scramb.charAt(index);  //finds letters in the same postion in the scrambled alphabet

        newMsg += b; //Adds up the letters
    }

    return newMsg;
}

在这一点上,我不知道如何去做,因为我刚刚开始学习字符串。如果你能帮忙,我将不胜感激。

-1index表示搜索没有找到。参见:String.indexOf()

尝试这样的事情:

private static final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final char[] scramb = alphabet.toChararray();

public static String cryptocodeM(String msg)
{
   if (null == msg || msg.isEmpty() )
      return msg;
   final StringBuilder newMsg = new StringBuilder(msg.length());
   shuffleArray(scramb);
   System.out.println(new String(scramb));
   msg = msg.toUpperCase(); 
   for (int x= 0; x < msg.length(); x++)
   {
      char a = msg.charAt(x);
      final int index = alphabet.indexOf(a);
      if (index > -1)
          a = scramb[index];
      newMsg.append(a);
   }
   return newMsg.toString();
}

public static void shuffleArray( char[] array )
{
    final Random rnd = new Random();
    for ( int i = array.length - 1 ; i > 0 ; --i )
    {
        final int index = rnd.nextInt( i + 1 );
        // Simple swap
        final char a = array[index];
        array[index] = array[i];
        array[i] = a;
    }
}

已编辑

问题是,char[] vs T...,即基元数组与对象数组...所以我只是从 SO 中查找了一个 shuffle,发现了这个:Random shuffling of an array