c语言插入字符到字符串中
时间: 2023-12-11 11:05:53 浏览: 59
可以使用字符串函数strcat()和strcpy()来实现在字符串中插入字符。
具体步骤如下:
1. 定义一个字符数组来表示字符串。
2. 使用strcpy()函数将原字符串复制到一个新的字符串中。
3. 使用for循环遍历新的字符串,将要插入的字符插入到指定位置。
4. 使用strcat()函数将新的字符串复制回原字符串中。
示例代码如下:
```
#include <stdio.h>
#include <string.h>
int main()
{
char str[100] = "Hello, world!";
char new_str[100];
char insert_char = '*';
int insert_index = 5;
int len = strlen(str);
int i, j;
strcpy(new_str, str);
for(i = 0; i <= len; i++)
{
if(i == insert_index)
{
for(j = len; j >= i; j--)
{
new_str[j+1] = new_str[j];
}
new_str[i] = insert_char;
break;
}
}
strcat(str, new_str);
printf("New string: %s", str);
return 0;
}
```
这个例子将在原字符串的第5个位置插入一个星号,输出结果为:
```
New string: Hello,* world!
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)