[英]How does one output into codeRunner to return with no spaces between the words in java?
Write algorithm that outputs a string with no spaces using caesar-cipher algorithm into coderunner.将使用凯撒密码算法输出没有空格的字符串的算法写入代码运行程序。 Lecturer mentioned string+= "" adds no spacing because the ASCI character 32 adds a space to the string.
讲师提到 string+= "" 不添加空格,因为 ASCI 字符 32 为字符串添加了空格。 I do not know how to implement this into code because confused with the string.length concept and how to use str += in this code.
我不知道如何将其实现到代码中,因为与 string.length 概念以及如何在此代码中使用 str += 混淆。 input encrypt2("are we human", 2) output: ctgygjwocp?
输入 encrypt2("我们是人类吗", 2) output: ctgygjwocp?
public class Tester {
public String encrypt(String plainText, int offset) {
String cipher = new String("");
char[] arr = plainText.toCharArray();
for (int i = 0; i<arr.length; i++){
int numericalVal = (int) arr[i];
if(Character.isUpperCase(arr[i])) {
cipher += (char) (((numericalVal+offset-65) %26) +65);
} else if (numericalVal == 32){
cipher+=arr[i];
} else {cipher += (char) (((numericalVal+offset-97) %26) +97);
}
}
return cipher;
}
public static void main(String[] args) {
String cipher +="";
system.out.println("are we human") }
}
public static String encrypt(String plainText, int offset) {
String cipher = "";
char[] arr = plainText.toCharArray();
for (char c : arr) {
if (Character.isUpperCase(c)) {
cipher += (char) (((c + offset - 65) % 26) + 65);
} else if (c == 32){
cipher+=""; //<---- append nothing if space
} else {
cipher += (char) (((c + offset - 97) % 26) + 97);
}
}
return cipher;
}
You can also do plainText = plainText.replaceAll(" ", "");你也可以做 plainText = plainText.replaceAll(" ", ""); and you won't have to check for character 32.
并且您不必检查字符 32。
public static String encrypt(String plainText, int offset) {
String cipher = "";
plainText = plainText.replaceAll(" ", "");
char[] arr = plainText.toCharArray();
for (char c : arr) {
if (Character.isUpperCase(c)) {
cipher += (char) (((c + offset - 65) % 26) + 65);
} else {
cipher += (char) (((c + offset - 97) % 26) + 97);
}
}
return cipher;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.