strstr仅在我的子字符串位于字符串末尾时才起作用
我现在写的这个程序遇到了一些问题。
- strstr仅在我的字符串末尾输出我的子字符串
- 之后它还会输出一些垃圾字符
- 我有“const char * haystack”的问题,然后添加输入,所以我用fgets和getchar循环
- 在它的工作方式的某个地方,它不仅在最后一个子串,但后来我输出了子串和其余的字符串ater that
这是我的主要内容:
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); }
和我的function:
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';