如何为加密文本保留空格

发布于 2025-01-11 03:52:45 字数 1119 浏览 0 评论 0原文

class Main {
  public static void main(String[] args) {
    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    String message = "how are you";
    int shift = -3;

    System.out.println(message);

    String eMessage = "";
   
    if(shift < 0) {
      int newShift = shift % 26 + 26;
      
      for (int i = 0; i < message.length(); i++) {
        int wordPosition = alphabet.indexOf(message.charAt(i));
        int numCipher = (wordPosition + newShift) % 26;
        char cipher = alphabet.charAt(numCipher);
        eMessage = eMessage + String.valueOf(cipher);
    else {  
      int newShift = shift % 26;
      for (int i = 0; i < message.length(); i++) {
        int wordPosition = alphabet.indexOf(message.charAt(i));
        int numCipher = (wordPosition + newShift) % 26;
        char cipher = alphabet.charAt(numCipher);
        eMessage = eMessage + String.valueOf(cipher);
      }
    }
      
    System.out.print(eMessage);
  }
}

它适用于单个单词,但是当我输入完整的句子时,消息的加密版本不会保留任何空格。相反,它将空格更改为 w。如何保留完整句子的空格? 我需要的例子- 输入:你好吗,输出:elt xob vlr ---- 我得到的例子 - 输入:你好吗,输出:eltwxobwvlr

class Main {
  public static void main(String[] args) {
    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    String message = "how are you";
    int shift = -3;

    System.out.println(message);

    String eMessage = "";
   
    if(shift < 0) {
      int newShift = shift % 26 + 26;
      
      for (int i = 0; i < message.length(); i++) {
        int wordPosition = alphabet.indexOf(message.charAt(i));
        int numCipher = (wordPosition + newShift) % 26;
        char cipher = alphabet.charAt(numCipher);
        eMessage = eMessage + String.valueOf(cipher);
    else {  
      int newShift = shift % 26;
      for (int i = 0; i < message.length(); i++) {
        int wordPosition = alphabet.indexOf(message.charAt(i));
        int numCipher = (wordPosition + newShift) % 26;
        char cipher = alphabet.charAt(numCipher);
        eMessage = eMessage + String.valueOf(cipher);
      }
    }
      
    System.out.print(eMessage);
  }
}

It works for single words, but when i type a full sentence the encrypted version of the message does not keep any spaces. It instead changes the spaces into w's. How do I keep the spaces for full sentences?
Example of what I need-
input: how are you, output: elt xob vlr ----
Example of what I get -
input:how are you, output: eltwxobwvlr

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文