简体   繁体   中英

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

Ok, so I'm trying to make a Caesar Cipher in java and I am trying to use the python approach, that I have used before, where you take the user input and check whether any of the letters are in the main string 'alphabet' and then use the shift value to find the current index of the character, then add the shift value to it and then add that current character to a new string, 'EncryptedMessage'.

I can't seem to figure out how to convert a string entered by the user, split it into individual characters and add it to a list 'chars' with the whitespaces.

I have tried to do it with a for loop and then print out the result, but it always stops as soon as there is a whitespace in the user entered string.

Can anyone please help me with what to do next. Also I am a new java programmer so please try not to give a really complex code to solve it.

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<>();
        }
      }

You can split the String into chars by toCharArray() , then you can shift them like this:

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);

Another way that doesn't use 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);

I haven't tested which one is faster, but I think the difference should be trivial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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