c语言在字符串中插入*
时间: 2023-12-27 11:03:00 浏览: 61
在C语言中,可以使用指针和循环来在字符串中插入`*`符号。以下是一个示例代码:
```c
#include <stdio.h>
int main() {
char str[100];
int i, j;
printf("请输入字符串:");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ') {
printf("* ");
} else {
printf("%c", str[i]);
}
}
return 0;
}
```
上述代码中,我们使用了`fgets()`函数来读取用户输入的字符串,并使用`for`循环遍历整个字符串。在循环中,如果当前字符是空格,则输出`* `,否则输出该字符本身。
注意,此代码假设用户输入的字符串不超过100个字符,如果需要处理更长的字符串,可以相应地调整数组大小。
相关问题
C语言如何在字符串中插入字符
在 C 语言中,要在字符串中插入字符,可以使用指针和循环来实现。具体的做法是,先将字符串中的每个字符都往后移动一个位置,然后在指定位置插入字符。以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
void insert_char(char *str, char ch, int pos) {
int len = strlen(str);
for (int i = len; i >= pos; i--) {
str[i+1] = str[i];
}
str[pos] = ch;
}
int main() {
char str[100] = "hello world";
insert_char(str, '!', 5);
printf("%s\n", str);
return 0;
}
```
在这个示例代码中,我们定义了一个 `insert_char` 函数,它接受三个参数:字符串指针 `str`、要插入的字符 `ch` 和插入的位置 `pos`。函数会先计算字符串的长度,然后从字符串的末尾开始循环,将每个字符往后移动一个位置,最后将字符插入到指定位置。在主函数中,我们调用了 `insert_char` 函数,在字符串中插入了一个感叹号。
c语言在字符串中间插入一个字符
要在C语言的字符串中间插入一个字符,可以用字符串函数strncpy()和strncat()来实现。首先使用strncpy()将插入位置之前的字符串复制到另一个字符串中,并在后面添加插入的字符,然后再使用strncat()将插入位置之后的字符串追加到新字符串中。以下是示例代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "hello world";
char str2[20] = "";
char insertChar = '*';
int insertIndex = 5;
strncpy(str2, str1, insertIndex);
str2[insertIndex] = insertChar;
strncpy(str2 + insertIndex + 1, str1 + insertIndex, strlen(str1) - insertIndex);
printf("%s\n", str2);
return 0;
}
```
运行结果为:
```
hell*o world
```
注意,这里假设插入位置为字符串的索引,索引从0开始。如果插入位置为字符指针,则可以使用指针运算符来计算插入位置的索引。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)