
如下图所示,题目要求生成一个“亲朋字符串”,具体规则如下: B2113 输出亲朋字符串

亲朋字符串定义如下: 给定字符串
s,它的“亲朋字符串”按以下规则生成:
s中第1个字符的ASCII值加第2个字符的ASCII值;s中第2个字符的ASCII值加第3个字符的ASCII值;输入格式:
输出格式:
输入:
1234输出:
cege在本题中,字符串的核心操作包括以下几点:
接下来,我们将通过三种代码实现来逐步解析。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 105; // 定义最大长度
char s1[N]; // 输入字符串
char s2[N]; // 输出字符串
int main() {
scanf("%s", s1); // 读取输入
int len = strlen(s1); // 获取字符串长度
for (int i = 0; i < len; i++) {
if (i == len - 1)
s2[i] = s1[i] + s1[0]; // 最后一个字符和第一个字符相加
else
s2[i] = s1[i] + s1[i + 1]; // 当前字符与下一个字符相加
}
s2[len] = '\0'; // 补充字符串结束符
cout << s2 << endl; // 输出结果
return 0;
}
1234后,程序依次计算: '1' + '2' = 49 + 50 = 99,ASCII值99对应字符'c';'2' + '3' = 50 + 51 = 101,ASCII值101对应字符'e';'3' + '4' = 51 + 52 = 103,ASCII值103对应字符'g';'4' + '1' = 52 + 49 = 101,ASCII值101对应字符'e'。cege。#include <iostream>
using namespace std;
const int N = 110;
char str[N];
int main() {
cin >> str; // 输入字符串
int i = 0;
while (str[i + 1]) { // 遍历到倒数第二个字符
char tmp = str[i] + str[i + 1]; // 当前字符与下一个字符相加
cout << tmp; // 输出结果
i++;
}
// 单独处理最后一个字符与第一个字符
cout << (char)(str[i] + str[0]) << endl;
return 0;
}
str[i + 1],对于初学者来说可能不够直观。#include <iostream>
#include <cstring>
using namespace std;
const int N = 110;
char str[N];
int main() {
cin >> str; // 输入字符串
int len = strlen(str); // 获取字符串长度
for (int i = 0; i < len; i++) {
char tmp = str[i] + str[(i + 1) % len]; // 当前字符与下一个字符(取模)相加
cout << tmp; // 输出结果
}
cout << endl; // 换行
return 0;
}
% len统一处理了首尾字符的关系,无需特殊判断。对于输入1234:
str[0] + str[1] = '1' + '2' = 99,输出c;str[1] + str[2] = '2' + '3' = 101,输出e;str[2] + str[3] = '3' + '4' = 103,输出g;str[3] + str[0] = '4' + '1' = 101,输出e。最终输出cege。
比较维度 | 我的做法 | 老师的第一种做法 | 老师的第二种做法 |
|---|---|---|---|
逻辑复杂度 | 较高,需要特判最后一个字符 | 较低,需要单独处理最后一个字符 | 最低,通过取模简化逻辑 |
代码简洁性 | 较为繁琐 | 中等 | 最为简洁 |
内存使用 | 使用额外数组存储结果 | 无额外数组 | 无额外数组 |
新手友好性 | 初学者容易理解 | 容易理解 | 可能需额外解释取模的用法 |
加强鲁棒性: 在所有实现中,都没有处理字符串为空的情况。如果输入为空,代码可能会出错。可以通过在读取输入后加上检查来解决:
if (strlen(str) == 0) {
cout << endl;
return 0;
}支持std::string: 如果将char数组替换为std::string,代码将更加现代化:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cin >> str;
int len = str.length();
for (int i = 0; i < len; i++) {
char tmp = str[i] + str[(i + 1) % len];
cout << tmp;
}
cout << endl;
return 0;
}适配Unicode字符: 如果需要支持更广泛的字符集,可以使用wchar_t或UTF-8编码。
通过这道亲朋字符串题目,我们不仅复习了C++中的字符串操作,还深入理解了下标控制、ASCII计算、以及边界处理等细节。在学习代码的过程中,不同的实现方式展现了从“解决问题”到“简洁优雅”的进阶过程。希望这篇文章能够帮助读者加深对C++字符串处理的理解,同时激发更多的编程灵感!