从以它们开头的单词中删除子串。(在C中)

时间:2014-12-07 12:24:03

标签: c

我正在尝试编写一小段代码(函数),只有当字符串的单词以这些子字符串开头时才会删除字符串中的子字符串。看看我到现在为止做了什么:

char *string="internship, is wonderful for people who like programming"
char *prefixes="intern wonder in pe"
char *delsubstr(char *string, const char *prefixes)

 {
 char *tokprefix;
 tokprefix=strtok(prefixes, " ");
 while(tokprefix)
    {
     size_t m = strlen(tokprefix);
     char *p = string;
     while ((p = strstr(p, tokprefix))!= NULL)
        { 

                {
                 char *q = p + m;
                 size_t n = strlen(q);
                 memmove(p, q, n + 1);
                 }
         }
     tokprefix=strtok(NULL, " ");
     }
 return string;
}

它的问题是它从任何地方移除了子串,而我只删除了从一开始就被删除的子串。此外,如果存在“intern”和“in”子串,我希望从字符串中删除较大的字符串,而不是较小的字符串。有人有任何想法/建议吗?我认为memmove之前的if条件就足够了,但我不确定。

1 个答案:

答案 0 :(得分:0)

  

我认为memmove之前的if条件就足够了,但是我可以   不确定。

除了修改前缀字符串文字的问题,这在上面的评论中处理,你大致正确:

     while ((p = strstr(p, tokprefix))!= NULL)
        { 
            if (p > string && p[-1] != ' ') // not at beginning of word?
                ++p;                        // then just advance pointer
            else                            // else remove start of word
                {
                 …