实现英文字母的移位功能
时间: 2023-08-28 14:38:32 浏览: 37
好的,以下是一个简单的C++代码,可以实现英文字母的移位功能:
```c++
#include <iostream>
#include <string>
using namespace std;
string shift_letters(string str, int shift) {
string result = "";
for (int i = 0; i < str.size(); i++) {
char c = str[i];
if (isalpha(c)) {
c = toupper(c);
c = ((c - 'A' + shift) % 26) + 'A';
}
result += c;
}
return result;
}
int main() {
string str = "Hello, World!";
int shift = 3;
string shifted_str = shift_letters(str, shift);
cout << "Original string: " << str << endl;
cout << "Shifted string: " << shifted_str << endl;
return 0;
}
```
该代码中的 `shift_letters` 函数接受一个字符串和一个整数作为参数,返回一个移位后的字符串。该函数中的循环迭代字符串中的每个字符,如果字符是字母,则将其转换为大写字母,并将其移位。移位后的字符将根据其在字母表中的位置计算得出,并使用模运算将其限制在 0 到 25 的范围内。最后,将移位后的字符添加到结果字符串中,并返回结果字符串。
在主函数中,我们定义了一个字符串和一个整数,然后调用 `shift_letters` 函数将字符串移位,并将移位后的字符串输出到控制台。