0

假设我想获取一个字符串并将每个字符(包括空格)增加 +n,然后打印出该新字符串。例如:

字符串 1 = '注意'

n = 7

所以字符串 2 将 = 'svvrgvba'

那有意义吗?无论如何,我不知道如何在这里起步。在将原始字符串的值增加 之前,是否需要将原始字符串拆分为其组成字符n?或者我可以使用类似的东西string.charAt(0) + n吗?

4

5 回答 5

1
String s1="look out";
int n=7;
char[] c= s1.toCharArray();
String f="";
for(int i=0 ; i<s1.length() ; i++) {
    if(c[i]==' ' || c[i]=='z'){
        c[i]= 'a';
    for(int j=1 ; j<n; j++){
c[i]++;
}

}
else{
     for(int j=0 ; j<n; j++){
    c[i]++;
    if(c[i]=='z'){

    c[i]= 'a';
    c[i]--;

}
}
}

f += c[i];
}
SOP(f);
于 2014-04-02T11:45:56.240 回答
0

尝试这个!!!

int n = 7;
n = n%26; //This will solve your problem if n is a large number like 1000
String str = "look out";
char[] arr = str.toCharArray();
int ascii = 0; 
int newAscii = 0;
String newStr ="";
char c;
for(int i=0; i<arr.length; i++) {
  ascii = arr[i];
  if(ascii == 32)
    newAscii = 97+n-1;
  else if((ascii+n)>122)
    newAscii = 97+(n-1-(122-ascii));
  else
    newAscii = ascii+7;
  c = (char)newAscii;
  newStr += c;
}
System.out.println(newStr);

如果您想在两者之间使用大写字母,那么也请使用此else if条件。

else if(ascii<=90)
    {
        if((ascii+n)>90) 
          newAscii = 65+(n-1-(90-ascii));
        else
          newAscii = ascii+n;
    }
于 2014-04-02T12:06:59.800 回答
0

Caesar coding uses this.

You can indeed just look at each character seperatly and loop through them, adding the values to each character just like Maroun told you :)

于 2013-11-06T18:12:45.530 回答
0

您正在寻找“ROT7”,是 ROT13 的维基百科文章

于 2013-11-06T18:01:16.637 回答
0

查看Ascii 表

l → 108  Adding 7 will result in 115 decimal value, which is the char s
o → 111  Adding 7 will result in 117 decimal value, which is the char v
o → 111  ..
k → 107  ..
  → 32   ..
o → 111  ..
u → 117  Adding 7 will result in 124, but you exceed 122 (z) by 2, so you convert it to b
t → 116  ..

svvrgvba如果你添加7到每个字符,你会得到。但是您应该注意添加7到时的情况t(实际上您在 之后得到一个十进制值z,在这种情况下您应该将其切换为a)。

于 2013-11-06T17:58:39.787 回答