【PTA数据结构 | C语言版】字符串连接操作
本专栏持续输出数据结构题目集,欢迎订阅。
文章目录
- 题目
- 代码
题目
请编写程序,将给定字符串 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;// 读取主串sfgets(s, MAX_LEN + 1, stdin);// 去除末尾的换行符if (s[strlen(s) - 1] == '\n') {s[strlen(s) - 1] = '\0';}// 读取待连接字符串tfgets(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;
}