从C语言的字符串中删除字符,出现冲突的类型错误

问题描述

我真的是编码新手,正在研究一个简单的问题,即使用c语言从字符串中删除字符。当我尝试编译代码时,我不断得到错误:“删除”类型冲突。我不知道为什么会收到此错误,因为代码似乎还可以。帮助将不胜感激。这是代码

#include <stdio.h>
#include <stdlib.h>

 int main()
{
    char ch,str[30],word[30];
    void remove(char[],char[],char);
    printf("enter the string\n");
    gets(str);
    printf("enter the character to move\n");
    ch=getchar();
    remove(str,word,ch);
    printf("converted to %s\n",word);

}

void remove(char str[],char word[],char c){
int j=0,k=0;
while(str[j++]!='\0'){
if(str[j]!=c)word[k++]=str[j];}
word[k]='\0';

}

解决方法

标头<stdio.h>已经具有一个名为remove的函数的声明。

int remove(const char *filename);

所以编译器会发出错误,因为在同一文件范围内两次用不同的类型声明了标识符remove

因此,将函数重命名为remove_copy

尽管如此,函数实现还是错误的。

在循环之内

while(str[j++]!='\0'){
if(str[j]!=c)word[k++]=str[j];}

由于条件的增加,您正在比较电流之后的下一个元素str[j]!=c

str[j++]

可以通过以下方式声明和实现该功能

char * remove_copy( char s1[],const char s2[],char c )
{
    char *p = s1;

    for ( ; *s2; ++s2 )
    {
        if ( *s2 != c ) 
        {
            *p++ = *s2;
        }
    }
    
    *p = '\0';

    return s1;
}  

请注意,函数gets是不安全的,并且C标准不再支持该函数。而是使用标准函数fgets

这是一个演示程序。

#include <stdio.h>
#include <string.h>

char * remove_copy( char s1[],char c )
{
    char *p = s1;

    for ( ; *s2; ++s2 )
    {
        if ( *s2 != c ) 
        {
            *p++ = *s2;
        }
    }
    
    *p = '\0';

    return s1;
}  

int main(void) 
{
    enum { N = 30 };
    char str[N],word[N];
    char c;
    
    printf( "Enter a string: " );
    fgets( str,N,stdin );
    
    str[ strcspn( str,"\n" ) ] = '\0';
    
    printf( "Enter a character to remove from the string: " );
    c = getchar();
    
    printf( "The result string is \"%s\"\n",remove_copy( word,str,c ) );
    
    return 0;
}

其输出可能看起来像

Enter a string: I am learning C++
Enter a character to remove from the string: +
The result string is "I am learning C"
,
  1. 更改功能名称。 remove已保留
  2. 您的功能仍然无法正常工作
#include <stdio.h>
char *strchrrem(const char *str,char *dest,char c)
{
    char *wrk = dest;
    do
    {
        if(*str != c) *wrk++ = *str;
    }while(*str++);

    return dest;
}

int main(void)
{
    char dest[64];

    printf("%s\n",strchrrem("Hello world.",dest,'l'));
}

https://godbolt.org/z/exqdE4

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...