c语言 编写一个函数,删除字符串中字符'a',并返回删除后字符串的长度。int delchar(char *str)
时间: 2024-03-11 10:50:45 浏览: 21
好的,这是一个简单的 C 语言函数,可以删除字符串中的 'a' 字符,并返回删除后字符串的长度:
```c
int delchar(char *str) {
int i = 0, j = 0;
while (str[i]) {
if (str[i] != 'a') {
str[j] = str[i];
j++;
}
i++;
}
str[j] = '\0';
return j;
}
```
函数接受一个指向字符串的指针,遍历字符串中的每个字符,如果字符不是 'a',就将其复制到新字符串中,最后将新字符串的结尾标记设置为 '\0',并返回新字符串的长度。
注意,此函数改变了原始字符串,因此可能需要在调用函数之前创建字符串的副本。
相关问题
用C语言编写一函数删除字符串中指定的字符,函数的原型为: void strdelch( char *str, char c ),并制作流程
好的,下面是实现函数的代码和流程图。
```c
#include <stdio.h>
#include <string.h>
void strdelch(char *str, char c) {
int i, j;
for (i = j = 0; str[i] != '\0'; i++) {
if (str[i] != c) {
str[j++] = str[i];
}
}
str[j] = '\0';
}
int main() {
char str[100];
char c;
printf("请输入一个字符串:");
scanf("%s", str);
getchar(); // 读取多余的回车符
printf("请输入要删除的字符:");
scanf("%c", &c);
strdelch(str, c);
printf("删除指定字符后的字符串为:%s\n", str);
return 0;
}
```
流程图如下:
![strdelch函数流程图](https://i.imgur.com/3rS6Q0u.png)
希望对您有所帮助!
用c语言编写一个程序,将一个指定字符插入到主字符串中指定位置。
下面是用C语言编写的将一个指定字符插入到主字符串中指定位置的程序:
```c
#include <stdio.h>
#include <string.h>
void insert(char *str, char ch, int pos) {
int len = strlen(str);
if (pos > len) {
printf("Error: invalid position!\n");
return;
}
memmove(str + pos + 1, str + pos, len - pos + 1);
str[pos] = ch;
}
int main() {
char str[100], ch;
int pos;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("Enter a character to insert: ");
ch = getchar();
printf("Enter the position to insert: ");
scanf("%d", &pos);
insert(str, ch, pos);
printf("Result: %s", str);
return 0;
}
```
程序中使用了字符串库函数 `strlen()` 和 `memmove()`,需要在程序开始处包含头文件 `string.h`。函数 `insert()` 接受三个参数:主字符串指针 `str`、要插入的字符 `ch` 和插入位置 `pos`。如果插入位置超过了主字符串的长度,函数会输出错误信息并返回。否则,函数使用 `memmove()` 函数将插入位置后面的字符向后移动一位,然后将要插入的字符放到插入位置上。
在 `main()` 函数中,程序首先读入一个字符串,然后读入要插入的字符和插入位置。接着调用 `insert()` 函数将字符插入到字符串中,并输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)