C-将角色的多个连续出现替换为一次出现

如何用C中的单个出现替换字符的多个连续出现?

例如,如果我有一个char myString[]="??hello?world????",我希望输出为?hello?world?

我找到了this链接,但是它替换了特定的模式。但是,如果重复字符的数目可变怎么办?

xxd1111 回答:C-将角色的多个连续出现替换为一次出现

可以使用一个循环来完成。

您在这里。

#include <stdio.h>

char * remove_duplicates( char *s,char c )
{
    for ( char *p = s,*q = s; *q; )
    {
        if ( *++q != c || *p != c )
        {
            *++p = *q;
        }
    }

    return s;
}

int main(void) 
{
    char s[] = "??hello?world????";

    printf( "\"%s\"\n",s );
    printf( "\"%s\"\n",remove_duplicates( s,'?' ) );

    return 0;
}

程序输出为

"??hello?world????"
"?hello?world?"

假定不应该将以null结尾的字符作为函数的参数提供。否则,该函数将没有effetc并返回相同的字符串。

,

以防其他答案 "??hello?world????"-> "?helo?world?"

#include <stdio.h>
#include<string.h>
int main()
{
    char myString[]="??hello?world????";
    int i,j,length=strlen(myString);
    char res[length];
    char prev;
    for(i=0,j=0;i<=length;i++)
    {
        if(i==0)
        {
            prev=myString[i];
            res[j]=prev;
            j++;
        }
        else
        {
            if(prev!=myString[i])
            {

                res[j]=myString[i];
                prev=res[j];
                j++;
            }
        }
    }
    printf("%s",res);
    return 0;
}
本文链接:https://www.f2er.com/3136405.html

大家都在问