本專欄持續輸出數據結構題目集,歡迎訂閱。
文章目錄
- 題目
- 代碼
題目
請編寫程序,將給定主串 s 中的子串 sub_s 替換成另一個給定字符串 t,再輸出替換后的主串 s。
輸入格式:
輸入給出 3 個非空字符串,依次為:主串 s、主串中待替換的子串 sub_s、將要替換掉 sub_s 的字符串 t。每個字符串占一行,長度不超過 1000 個字符,以回車結束(回車不算在字符串內)。
題目保證替換后的主串長度仍然不超過 1000 個字符。
輸出格式:
在一行中輸出替換后的主串 s。
輸入樣例 1:
This is a simple test.
is
at
輸出樣例 1:
That at a simple test.
輸入樣例 2:
This is a test.
simple
what
輸出樣例 2:
This is a test.
代碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int replace_sub_str(const char *str, const char *substr, const char *repstr, char *result) {const char *p = str;char *t = result;int count = 0;size_t sub_len = strlen(substr);size_t rep_len = strlen(repstr);while (*p) {if (strncmp(p, substr, sub_len) == 0) {count++;memcpy(t, repstr, rep_len);t += rep_len;p += sub_len;} else {*t++ = *p++;}}*t = '\0';return count;
}int main() {char s[10001] = {0};char sub_s[10001] = {0};char t[10001] = {0};// 讀取輸入字符串fgets(s, sizeof(s), stdin);s[strcspn(s, "\n")] = 0; // 移除換行符fgets(sub_s, sizeof(sub_s), stdin);sub_s[strcspn(sub_s, "\n")] = 0;fgets(t, sizeof(t), stdin);t[strcspn(t, "\n")] = 0;char result[1001] = {0};int num = replace_sub_str(s, sub_s, t, result);printf("%s\n", result);return 0;
}