【发布时间】:2021-01-16 06:51:02
【问题描述】:
我正在尝试用存储在数组中的字符来切换字符,而我的老师和我被卡住了,
一个例子是:
abcdef 会切换到 zyxwvu
或
你好会切换到 spool
下面是上述代码的图片和链接
【问题讨论】:
我正在尝试用存储在数组中的字符来切换字符,而我的老师和我被卡住了,
一个例子是:
abcdef 会切换到 zyxwvu
或
你好会切换到 spool
下面是上述代码的图片和链接
【问题讨论】:
此代码将帮助您理解流程:
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);
}
【讨论】:
首先,您应该将i >= alpha.length 更改为i < msg.length(),但这并不重要,因为您所做的将不起作用。
msg.replace(...) 调用不会改变msg 的值,但即使改变了,结果也不会是你想要的,因为你会把a 改为z,然后你会改变z 回a。
退后一步,重新思考你想要做什么。
提示:使用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̂
【讨论】: