【问题标题】:How to censor a word in a char array? [closed]如何审查 char 数组中的单词? [关闭]
【发布时间】:2016-06-22 05:53:01
【问题描述】:

如何在 char 数组中找到一个单词并使用通配符 (*) 对其进行审查?

我试图找到第一次出现的单词,但失败了。我已经尝试过了,它也没有工作。我是新手,我已经尝试了 5 个小时。

int main()  
{
    int w,q;
    char l,m;
    char *arr, *swear;
    int i,a,t,k,z;

    printf("Enter a word which is not allowed.");
    scanf("%s", swear);
    printf("Now enter a word.");
    scanf("%s", arr);

    for(a=0; swear[a]!='\0'; ++a); //finding length of swear
    for(t=0;arr[t]!='\0';t++);    // finding length of arr

    for(i=0,k=0;k<t & i<t;i++,k++)
    {
        arr[i]=l;
        swear[k]=m;
        if(strstr(swear,arr))
            arr[i]='*';
        else
            break;
    }

    for(z=0;z<t;z++)
    {
        printf("%c",arr[z]);
    }
    return(0);
}

【问题讨论】:

  • 这不是 cmets 的工作方式。评论可以解释为什么你在做你正在做的事情而不是你正在做的事情。不妨习惯于解释为什么而不是解释什么。
  • 请:显示更多代码,尤其是arr 是如何声明的。阅读MCVE
  • 感谢我编辑了我的答案
  • scanf 需要足够大的缓冲区来存储字符串而不是悬空指针。尝试类似char arr[1024], swear[1024]; 并防止scanf 写出缓冲区scanf("%1024s",发誓);`

标签: c arrays string replace


【解决方案1】:

因此,您想用由'*' 组成的等长字符串覆盖所有出现的字符串。为此,您需要迭代地获取指向字符串出现的指针,并且您还需要它的长度来知道您必须使用多少 '*'

size_t swearLength = strlen(swear); // swear is assumed null-terminated
char *here = arr;
while ((here = strstr(here, swear)) {
    memset(here, '*', swearLength);
    here += swearLength;  // to avoid searching what's already censored
}

strstr 如果找不到 swear 将返回 null,因此循环将终止

【讨论】:

  • 建议,在 memset 行之后,添加:here += swearLength; 没有必要重新检查你刚刚写的内容。
  • 对我来说看起来不错,否决者关心启发?
  • 与其他答案相同的问题:strstr 不是 word 函数。
  • @RadLexus 到目前为止,OP 的代码并没有这样做,他也没有要求这样做。
  • @Alnitak:“我怎样才能在 char 数组中找到 word ...”也就是说,仅此一项任务就值得一篇简短的博士论文 - 并且已被问到很多很多次之前在SO上。查看 OP 的代码,我同意这远远不是主要问题(甚至认为 OP 花了整整“5 个小时”来解决它;我考虑过比这更长的具体问题)。
猜你喜欢
  • 2017-12-18
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2012-10-30
  • 2021-11-27
  • 2014-03-28
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多