繁体   English   中英

使用带空格的字符串,将其拆分为单个字符,并将其添加到字符列表

[英]Taking string with whitespaces, splitting it into individual characters, and adding it to a char list

好的,所以我试图在Java中创建一个Caesar密码,并且尝试使用以前使用的python方法,在此方法中,您将接收用户输入并检查主字符串'alphabet中是否存在任何字母',然后使用移位值查找字符的当前索引,然后向其添加移位值,然后将该当前字符添加至新字符串'EncryptedMessage'。

我似乎无法弄清楚如何转换用户输入的字符串,将其拆分为单个字符,然后将其添加到带有空格的“字符”列表中。

我尝试过使用for循环来执行此操作,然后打印出结果,但是只要用户输入的字符串中有空格,它就会始终停止。

谁能帮我下一步做什么。 我也是一个新的Java程序员,所以请不要给出真正复杂的代码来解决它。

import java.util.Scanner;
import java.util.ArrayList;
public class CaesarCipher {
    protected final static String alphabet = "abcdefghij klmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890,.'(){}[]";
    public static void main(String[] args) {
        //Declares the scanner class that is used to read the user's input from the keyboard
        Scanner input = new Scanner(System.in);
        //Asking the user for a shift value for encryption
        System.out.println("Please enter a shift value:");
        int shiftVal = input.nextInt();
        //Asks the user for a string that they want to be encrypted
        System.out.println("Please enter the message that you want to be encrypted:");
        String msg = input.next();
        //A String that will store the encrypted message
        String encryptedMsg = "";
        ArrayList<Character> chars = new ArrayList<>();
        }
      }

您可以通过toCharArray()将String拆分为chars,然后可以像这样移动它们:

int shiftVal = 5;
String whatever = "dfsfsdf";
char[] whateverArr = whatever.toCharArray();
for (int i = 0; i < whateverArr.length; i++) {
    whateverArr[i] += shiftVal;
}
String whateverEnc = String.valueOf(whateverArr);

另一种不使用toCharArray()

char[] whateverArr = new char[whatever.length()];
for (int i = 0; i < whateverArr.length; i++) {
    whateverArr[i] = (char) (whatever.charAt(i) + shiftVal);
}
String whateverEnc = String.valueOf(whateverArr);

我还没有测试过哪一个更快,但是我认为区别应该很小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM