【问题标题】:Switching Letters to characters in an array [closed]将字母转换为数组中的字符[关闭]
【发布时间】:2021-01-16 06:51:02
【问题描述】:

我正在尝试用存储在数组中的字符来切换字符,而我的老师和我被卡住了,

一个例子是:

abcdef 会切换到 zyxwvu

你好会切换到 spool

下面是上述代码的图片和链接

Picture to code here

Link to code (If you can access it

【问题讨论】:

标签: java arrays list


【解决方案1】:

此代码将帮助您理解流程:

  public static void main(String[] args) {
    // ****************************************
    // ** Call your function to test them in **
    // ** the main function here.            **
    // ****************************************

    String msg = "Yes Sir How may I help you ";

    //Alphabet 
    String alpha[] = {"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"};

    //Alphabet Reversed
    String alpharev[] = {"z", "y", "x", "w", "v", "u", "t", "s", "r", "q", "p", "o", "n", "m", "l", "k", "j", "i", "h", "g", "f", "e", "d", "c", "b", "a"};

    String converted = "";
    for (int i = 0; i < msg.length(); i++){

      if(msg.charAt(i) >= 'a'){
        converted+=alpharev[msg.charAt(i) - 'a'];
      } else if(msg.charAt(i) >= 'A'){
        converted+=alpharev[msg.charAt(i) - 'A'];
      } else{
        converted+= msg.charAt(i) ;
      }
    }
    System.out.println("Message: " + converted);
  }

【讨论】:

  • 感谢您的帮助,现在快速添加您发送的内容,如果我能够将其反转回 svool --> 你好,我会怎么做
  • 只需将 String alpha[] 的值交换为 String alpharev[],反之亦然
  • //字母字符串 alpha[] = {"z", "y", "x", "w", "v", "u", "t", "s", " r”、“q”、“p”、“o”、“n”、“m”、“l”、“k”、“j”、“i”、“h”、“g”、“f” ,“e”,“d”,“c”,“b”,“a”}; //字母反转字符串 alpharev[] = {"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"};
  • 我改变了数组中的值——就像你说的那样链接:imgur.com/97AeIs4我做错了什么
  • 其实不要做任何事情上面的代码也可以用于反向...
【解决方案2】:

首先,您应该将i &gt;= alpha.length 更改为i &lt; msg.length(),但这并不重要,因为您所做的将不起作用。

msg.replace(...) 调用不会改变msg 的值,但即使改变了,结果也不会是你想要的,因为你会把a 改为z,然后你会改变za

退后一步,重新思考你想要做什么。


提示:使用msg.toCharArray(),然后更新数组中的字符,完成后转换回String

static String switchLetters(String text) {
    char[] chars = Normalizer.normalize(text, Normalizer.Form.NFD).toCharArray();
    for (int i = 0; i < chars.length; i++) {
        char ch = chars[i];
        if (ch >= 'a' && ch <= 'z')
            chars[i] = (char) ('z' - (ch - 'a'));
        else if (ch >= 'A' && ch <= 'Z')
            chars[i] = (char) ('Z' - (ch - 'A'));
    }
    return new String(chars);
}

测试

System.out.println(switchLetters("abcdef"));
System.out.println(switchLetters("hello"));
System.out.println(switchLetters("Yes Sir How may I help you "));
System.out.println(switchLetters("héllô"));

输出

zyxwvu
svool
Bvh Hri Sld nzb R svok blf 
sv́ool̂

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 2011-09-19
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多