【问题标题】:strstr works only if my substring is at the end of stringstrstr 仅在我的子字符串位于字符串末尾时才有效
【发布时间】:2015-12-02 17:15:06
【问题描述】:

我现在正在编写的程序遇到了一些问题。

  1. strstr 仅在我的字符串结尾处输出我的子字符串
  2. 之后还会输出一些垃圾字符
  3. 我遇到了“const char *haystack”的问题,然后向它添加输入,所以我使用 fgets 和 getchar 循环来解决
  4. 在某个地方,它使用了一个子字符串,该子字符串不仅位于末尾,而且随后我输出了子字符串,而字符串的其余部分在该处发生

这是我的主要内容:

int main() {
    char    haystack[250],
            needle[20];

    int     currentCharacter,
            i=0;

    fgets(needle,sizeof(needle),stdin); //getting my substring here (needle)

    while((currentCharacter=getchar())!=EOF) //getting my string here (haystack)

    {
        haystack[i]=currentCharacter;
        i++;
    }

    wordInString(haystack,needle);

    return(0);
}

和我的功能:

int wordInString(const char *str, const char * wd)
{
    char *ret;
    ret = strstr(str,wd);

    printf("The substring is: %s\n", ret);
    return 0;
}

【问题讨论】:

  • haystack 中缺少一个终止符 '\0',会给你带来各种麻烦。

标签: c strstr


【解决方案1】:

您使用fgets() 读取一个字符串,使用getchar() 读取另一个字符串,直到文件末尾。两个字符串的末尾都有一个尾随'\n',因此strstr() 只能匹配位于主字符串末尾的子字符串。 此外,您不会在haystack 的末尾存储最终的'\0'。您必须这样做,因为haystack 是一个本地数组(自动存储),因此不会隐式初始化。

您可以这样解决问题:

//getting my substring here (needle)
if (!fgets(needle, sizeof(needle), stdin)) {
    // unexpected EOF, exit
    exit(1);
}
needle[strcspn(needle, "\n")] = '\0';

//getting my string here (haystack)
if (!fgets(haystack, sizeof(haystack), stdin)) {
    // unexpected EOF, exit
    exit(1);
}
haystack[strcspn(haystack, "\n")] = '\0';

【讨论】:

  • 1+ 用于使用strcspn() :-)
  • 限制读取循环不溢出haystack 也很好...... ;-)
  • 我看到了,我完全同意针,因为我希望它仅限于 1 行,但是当涉及到 haystack 时 - 我希望它超过 1 行。考虑到这一点,我可以以某种方式做到这一点,这样我就不需要将 haystack 定义为 [250] 元素数组,并且它会在我结束输入时计算元素吗?但随后会出现另一个问题,因为我的针中没有 \n,但我会将它放在大海捞针中 - 因此,如果在我的大海捞针中将针分成 2 行,它将不匹配。
  • 您可以在将标准输入的其余部分读入 haystack 缓冲区时将 neelines 转换为空格。
猜你喜欢
  • 1970-01-01
  • 2019-09-26
  • 2023-03-27
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 2014-12-04
相关资源
最近更新 更多