题干解读:将输入的字符串中的字符按字母表向后移动n位,并输出结果.
解题思路:由于字符的移动规则是按字母表移动,所以先写一个move函数,定义一下字符的移动规则,然后遍历字符串,将其中的每一个字符都调用move函数,让后输出即可.
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
char move(char c, int n) {
n = n % 26;
if (c + n > 'z') {
return c + n - 'z' + 'a'-1;
} else {
return c + n;
}
}
string encode(string s, int n) {
for (int i = 0; i < s.length(); i++) {
s[i] = move(s[i], n);
}
return s;
}
int main() {
int n;
string s;
cin >> n;
cin >> s;
s = encode(s, n);
cout << s;
}

京公网安备 11010502036488号