c语言输入串s和串t,并且在串s的第n个位置之前插入串t,然后输出插入后的串
时间: 2024-01-24 13:17:13 浏览: 24
以下是一个基本的 C 语言程序,实现了在字符串 s 的第 n 个位置之前插入字符串 t 的功能:
```c
#include <stdio.h>
#include <string.h>
#define MAXLEN 100
void insert_string(char *s, char *t, int n);
int main() {
char s[MAXLEN], t[MAXLEN];
int n;
printf("Enter the string s: ");
scanf("%s", s);
printf("Enter the string t: ");
scanf("%s", t);
printf("Enter the position to insert t: ");
scanf("%d", &n);
insert_string(s, t, n);
printf("The resulting string is: %s\n", s);
return 0;
}
void insert_string(char *s, char *t, int n) {
int len_s = strlen(s);
int len_t = strlen(t);
if (n > len_s) {
printf("Error: position out of range.\n");
return;
}
// 后移 s 中第 n 个字符及之后的字符
for (int i = len_s; i >= n; i--) {
s[i + len_t] = s[i];
}
// 将 t 插入到 s 中第 n 个字符的位置
for (int i = 0; i < len_t; i++) {
s[n + i] = t[i];
}
}
```
这个程序首先读入两个字符串 s 和 t,以及要插入 t 的位置 n。然后调用 `insert_string` 函数将 t 插入到 s 中第 n 个字符的位置。最后输出插入后的结果字符串。
值得注意的是,在 `insert_string` 函数中,我们首先计算了 s 和 t 的长度,如果 n 大于 s 的长度,则输出错误信息并直接返回。否则,我们先将 s 中第 n 个字符及之后的字符后移 len_t 个位置,然后将 t 插入到 s 中第 n 个字符的位置。