用c语言将一个字符串输入到另一个字符串指定位置
时间: 2024-05-16 07:13:58 浏览: 9
可以使用字符串函数 `strcpy()` 和 `strcat()` 来实现这个功能。
假设我们要将字符串 `src` 插入到字符串 `dest` 的第 `pos` 个位置处,可以按照以下步骤进行操作:
1. 使用 `strncpy()` 函数将 `dest` 的前 `pos-1` 个字符复制到一个临时字符串 `temp` 中,同时在 `temp` 的第 `pos` 个位置处添加一个字符串结束符 `\0`。
2. 使用 `strcat()` 函数将 `src` 追加到 `temp` 的末尾。
3. 使用 `strcat()` 函数将 `dest` 的第 `pos` 个字符开始的剩余部分追加到 `temp` 的末尾。
4. 最后使用 `strcpy()` 函数将 `temp` 复制回 `dest`。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
void insert_string(char *dest, char *src, int pos) {
char temp[strlen(dest) + strlen(src) + 1];
strncpy(temp, dest, pos - 1);
temp[pos - 1] = '\0';
strcat(temp, src);
strcat(temp, dest + pos - 1);
strcpy(dest, temp);
}
int main() {
char dest[20] = "hello,world";
char src[] = " beautiful";
int pos = 6;
insert_string(dest, src, pos);
printf("%s\n", dest);
return 0;
}
```
输出结果为:
```
hello beautiful,world
```