【PTA数据结构 | C语言版】字符串截取子串操作
本专栏持续输出数据结构题目集,欢迎订阅。
文章目录
- 题目
- 代码
题目
请编写程序,截取给定字符串 s 中从第 pos 个字符开始的 len 个字符并输出。
输入格式:
输入首先在一行中给出非空主串 s,不超过 1000 个字符,以回车结束(回车不算在字符串内)。第二行给出位序 pos 和待截取的字符个数 len(均为正整数,保证不超过 s 的长度)。
输出格式:
在一行中输出截取到的字符串。
输入样例 1:
This is a test.
6 6
输出样例 1:
is a t
输入样例 2:
This is a test.
7 12
输出样例 2:
s a test.
代码
#include <stdio.h>
#include <string.h>int main() {char s[1001];int pos, len;// 读取输入字符串fgets(s, sizeof(s), stdin);// 去除换行符if (s[strlen(s)-1] == '\n') {s[strlen(s)-1] = '\0';}// 读取截取位置和长度scanf("%d %d", &pos, &len);// 计算实际截取的字符数int actual_len = len;int str_len = strlen(s);if (pos + actual_len - 1 > str_len) {actual_len = str_len - pos + 1;}// 截取并输出子字符串if (actual_len > 0) {s[pos + actual_len - 1] = '\0'; // 截断字符串printf("%s\n", s + pos - 1); // 从pos-1位置开始输出} else {printf("\n"); // 无字符可截取时输出空行}return 0;
}