繁体   English   中英

仅当我的子字符串位于字符串末尾时,strstr才有效

[英]strstr works only if my substring is at the end of string

我现在编写的程序遇到了两个问题。

  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;
}

您可以使用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';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM