用字符指针作函数参数编程实现如下功能:在字符串中删除与某字符相同的字符。 **输入格式要求:"%s" 输入提示信息: "Input a string:" "Input a character:" **输出格式要求:"Results:%s\n" 程序运行示例1如下: Input a string:hello,world! Input a character:o Results:hell,wrld! 请按如下框架编程: #include <stdio.h> #include <string.h> #define N 100 void Squeeze(char *s, char c); int main() { char str[20], ch; printf("Input a string:"); gets(str); printf("Input a character:"); ch = getchar(); ...... printf("Results:%s\n", str); return 0; } void Squeeze(char *s, char c) { ...... }
时间: 2023-12-03 15:46:19 浏览: 36
完整代码如下:
```
#include <stdio.h>
#include <string.h>
#define N 100
void Squeeze(char *s, char c);
int main()
{
char str[N], ch;
printf("Input a string:");
gets(str);
printf("Input a character:");
ch = getchar();
Squeeze(str, ch);
printf("Results:%s\n", str);
return 0;
}
void Squeeze(char *s, char c)
{
int i, j;
for (i = j = 0; s[i] != '\0'; i++)
{
if (s[i] != c)
{
s[j++] = s[i];
}
}
s[j] = '\0';
}
```
函数`Squeeze`实现了删除字符串中与指定字符相同的字符。具体实现方法是,从头到尾遍历字符串`s`,如果当前字符不是指定的字符`c`,则将该字符存入`s`的另一个空间,最后在新的字符串末尾加上`\0`表示字符串结束。
相关问题
用字符指针作函数参数编程实现如下功能:在字符串中删除与某字符相同的字符。
以下是一个示例代码,可以实现在字符串中删除与某字符相同的字符:
```c
void delete_char(char *str, char c) {
char *p = str;
while (*p) {
if (*p == c) {
char *q = p;
while (*q) {
*q = *(q + 1);
q++;
}
} else {
p++;
}
}
}
```
在这个函数中,我们首先定义了一个字符指针 `p`,它指向字符串的开头。然后我们使用一个 while 循环来遍历整个字符串,如果当前字符等于要删除的字符 `c`,我们就定义另一个字符指针 `q`,它指向当前字符,然后使用另一个 while 循环来将后面的字符依次向前移动一个位置,最后将字符串的长度减一。如果当前字符不等于要删除的字符,我们就将指针 `p` 向后移动一个位置。
使用这个函数的方法很简单,只需要将要删除字符的字符串和要删除的字符作为参数传递给函数即可:
```c
char str[] = "hello world";
delete_char(str, 'l');
printf("%s\n", str); // 输出 "heo word"
```
注意,这个函数只能删除一个字符,如果要删除多个字符,需要多次调用这个函数。
用字符数组作函数参数编程实现如下功能:在字符串中删除与某字符相同的字符。 **提示信息: "Input a string:" "Input a character:" **输入格式要求:"%s" **输出格式要求:"Results:%s\n"
以下是实现该功能的代码:
```c
#include <stdio>
#include <string.h>
void deleteChar(char str[], char ch);
int main() {
char str[100];
char ch;
printf("Input a string:");
scanf("%s", str);
printf("Input a character:");
scanf(" %c", &ch);
deleteChar(str, ch);
printf("Results:%s\n", str);
return 0;
}
void deleteChar(char str[], char ch) {
int i, j;
int len = strlen(str);
for (i = 0, j = 0; i < len; i++) {
if (str[i] != ch) {
str[j++] = str[i];
}
}
str[j] = '\0';
}
```
该程序首先提示用户输入一个字符串和一个字符,然后调用 `deleteChar()` 函数,将字符串中与该字符相同的字符删除。最后输出处理后的字符串。
`deleteChar()` 函数的实现很简单,使用两个指针 `i` 和 `j` 分别指向原字符串和新字符串,遍历原字符串中的每个字符,如果该字符不等于给定字符,则将其复制到新字符串中。最后在新字符串的结尾处添加一个空字符结束字符串。