现在我有以下代码,我试图让代码附加到字符串而不是system.out.println。我知道这个措辞很奇怪,但不知道怎么说。
char[] c = inputString.toCharArray();
for(char ch : c)
{
if(ch <=88 && ch>=65 || ch<=120 && ch>=97)
System.out.print(Character.valueOf((char) (ch+2)));
else
if (ch =< 1)
System.out.print(Character.valueOf((char) (ch-24)));
else
if (ch == 2)
System.out.print(Character.valueOf((char) (ch-24)));
else
System.out.print(ch);
答案 0 :(得分:3)
您只需要在c[] array
旁边定义一个字符串,然后通过此运算符+=
将这些字符添加到其中,最后您将获得所需内容的完整字符串,因此
char[] c = inputString.toCharArray();
String str = "";
for(char ch : c)
{
if(ch <=88 && ch>=65 || ch<=120 && ch>=97) {
str += Character.valueOf((char) (ch+2));
} else{
if (ch =< 1){
str += Character.valueOf((char) (ch-24));
}else {
if (ch == 2){
str += Character.valueOf((char) (ch-24));
}else{
str += ch;
}
}
}
}
// now str is the result that you want an you can do any operation on it as you wish
答案 1 :(得分:0)
你也可以使用StringBuffer,如下所示:
char[] c = inputString.toCharArray();
StringBuffer strBf = new StringBuffer();
String str;
for(char ch : c){
if(ch <=88 && ch>=65 || ch<=120 && ch>=97) {
strBf.append(Character.valueOf((char) (ch+2)));
} else{
if (ch =< 1){
strBf.append(Character.valueOf((char) (ch-24)));
}else {
if (ch == 2){
strBf.append(Character.valueOf((char) (ch-24)));
}else{
strBf.append(ch);
}
}
}
}
str = strBf.toString();