c - 从以子字符串开头的单词中删除子字符串。(C 语言)

标签 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 条件就足够了,但我不确定。

最佳答案

I think an if condition before the memmove could be enough, but I'm not sure.

除了上面注释中处理的修改前缀字符串文字的问题之外,您大致是正确的:

     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
                {
                 …

关于c - 从以子字符串开头的单词中删除子字符串。(C 语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27342561/

相关文章:

c++ - 编译和代码优化

c++ - 发现两个字符串是循环的

c - strtok() 问题获取字符串的第一个标记

c - 使用非阻塞套接字时,recv 无响应

c - 时间测量中的负值?

c - fflush(stdin) 不能在 cygwin 中用 gcc 编译,但可以用 visual studio 2010 编译

c - 如何将值从结构复制到字符数组

c++ - C++ 中 CPU 使用率降低 : declaring as unsigned int or not?

c - 未知的 CMake 命令 ADD_TESH_FACTORIES

c - 我正在尝试返回第一个持有值(value)项目的节点,如果没有找到则返回 NULL