簡體   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