本专栏持续输出数据结构题目集,欢迎订阅。
题目
请编写程序,将给定字符串 t 连接在另一个给定字符串 s 的末尾。
输入格式:
输入先后给出主串 s 和待连接的字符串 t,每个非空字符串占一行,不超过 1000 个字符,以回车结束(回车不算在字符串内)。
输出格式:
在一行中输出将 t 连接在 s 末尾后的结果字符串 s。
如果连接后的字符串长度超过了 1000 个字符,则不要连接,而是在一行中输出 错误:连接将导致字符串长度超限。,并且在第二行输出原始主串 s。
输入样例:
This is
a test.
输出样例:
This is a test.
代码
#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000 // 最大字符串长度限制
int main() {
char s[MAX_LEN + 1]; // 主串
char t[MAX_LEN + 1]; // 待连接字符串
int pos;
// 读取主串s
fgets(s, MAX_LEN + 1, stdin);
// 去除末尾的换行符
if (s[strlen(s) - 1] == '\n') {
s[strlen(s) - 1] = '\0';
}
// 读取待连接字符串t
fgets(t, MAX_LEN + 1, stdin);
// 去除末尾的换行符
if (t[strlen(t) - 1] == '\n') {
t[strlen(t) - 1] = '\0';
}
// 计算连接后的长度
int len_s = strlen(s);
int len_t = strlen(t);
int total_len = len_s + len_t;
// 判断是否超限
if (total_len > MAX_LEN) {
printf("错误:连接将导致字符串长度超限。\n");
printf("%s\n", s);
} else {
// 执行连接操作
strcat(s, t);
// 输出结果
printf("%s\n", s);
}
return 0;
}
3938

被折叠的 条评论
为什么被折叠?



