假设我想获取一个字符串并将每个字符(包括空格)增加 +n,然后打印出该新字符串。例如:
字符串 1 = '注意'
n = 7
所以字符串 2 将 = 'svvrgvba'
那有意义吗?无论如何,我不知道如何在这里起步。在将原始字符串的值增加 之前,是否需要将原始字符串拆分为其组成字符n
?或者我可以使用类似的东西string.charAt(0) + n
吗?
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);
尝试这个!!!
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;
}
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 :)
您正在寻找“ROT7”,这是 ROT13 的维基百科文章
查看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
)。