如何在字符串中的每个字符之间生成随机字符?

How to generate random characters between each character within a string?

我有一个代码,我必须在其中实现一个接口,目的是获取一个像 mycookisred 这样的字符串,然后在每个字符串之间插入原始单词中的随机字符。在这种情况下,这可能会阻碍,例如meynciovoksidswrbendn。另一个例子,为了完整起见:mycleverpassword 字符串可以变成 mxyschlmezvievrppeaysisvwcoorydc.

我知道我的代码不完全适合这个目的,但是有人可以帮助或指导我从这个起点开始做什么吗?

   import java.util.Random;

  public class password implements Encryptable
{
    private String message;
    private boolean encrypted;
    private int shift;
    private Random generator;

    public password(String msg)
    {
        message = msg;
        encrypted = false;
        generator = new Random();
        shift = generator.nextInt(10) + 5;
    }
    public void encrypt()
    {
        if (!encrypted)
        {
            String masked = "";
            for ( int index = 0; index < message.length(); index++)
            masked = masked + (char)(message.charAt(index) +shift);
            message = masked;
            encrypted = true;
        }
    }
    public String decrypt()
    {
        if (!encrypted)
        {
            String unmasked = "";
            for ( int index = 0; index < message.length(); index++)
            unmasked = unmasked + (char)(message.charAt(index) - shift);
            message = unmasked;
            encrypted = false;
        }
        return message;
    }
    public boolean isEncrypted()
    {
        return encrypted;
    }
    public String toString()
    {
        return message;
    }

}
public class passwordTest
{
  public static void main(String[] args)
  {
      password hide = new password("my clever password");
      System.out.println(hide);

      hide.encrypt();
      System.out.println(hide);

      hide.decrypt();
      System.out.println(hide);
  }


}


public interface Encryptable
{
    public void encrypt();
    public String decrypt();
}

只需使用它来随机化和规范化字符串:

private String randomize(String s) {
    String re = "";
    int len = s.length();
    for(int i = 0; i < len - 1; i++) {
        char c = s.charAt(i);
        re += c;
        re += (char) (generator.nextInt('z' - 'a') + 'a');
    }
    re += s.charAt(len - 1);
    return re;
}

private String normalize(String s) {
    String re = "";
    for(int i = 0; i < s.length(); i+=2) {
        re += s.charAt(i);
    }
    return re;
}

而 Class 应该以大写字符开头。你不需要,但是例如 Eclipse 会哭。