我正在尝试编写一小段代码(函数),仅当字符串中的单词以这些子字符串开头时才删除字符串中的子字符串。看看到目前为止我已经尝试过什么:
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/