作品的strstr只有当我子是字符串的结尾 [英] strstr works only if my substring is at the end of string
问题描述
我遇到了几个与我现在正在写程序的问题。
- 输出的strstr子我只有当它在我的字符串在这里输入的形象描述
- 它也可以输出一些垃圾字符后在这里输入的形象描述
- 我已经受够了为const char *大海捞针的问题,然后添加输入到它,所以我用fgets和循环的getchar 做到了
- 某处它与已不仅是底,但后来我输出子和字符串亚特那剩下的子串的工作方式
这是我主要的:
INT的main(){
焦炭草垛[250]
针[20]; INT currentCharacter,
I = 0; 与fgets(针的sizeof(针),标准输入); //这里让我的子(针) 而((currentCharacter =的getchar())!= EOF)//这里让我的字符串(大海捞针) {
草垛[I] = currentCharacter;
我++;
} wordInString(草堆,针); 返回(0);
}
和我的功能:
INT wordInString(为const char * str中,为const char * WD)
{
字符* RET;
RET =的strstr(STR,WD); 的printf(子字符串是:%S \\ n,RET);
返回0;
}
您读取一个字符串与fgets()
和其他与的getchar( )
高达文件的末尾。有一个尾随的'\\ n'
在两个字符串的结尾,因此的strstr()
只能匹配子串如果它是在主字符串的末尾。
此外,你没有保存最后'\\ 0'
在草垛年底
。你必须这样做,因为草垛
是一个局部阵列(自动存储),因此未初始化含蓄。
您可以纠正这个问题是这样的:
//这里让我的子(针)
如果(!与fgets(针的sizeof(针),标准输入)){
//意外EOF,退出
出口(1);
}
针[strcspn(针\\ n)] ='\\ 0';//这里让我的字符串(大海捞针)
如果(!与fgets(草堆,sizeof的(干草堆),标准输入)){
//意外EOF,退出
出口(1);
}
草垛[strcspn(草堆,\\ n)] ='\\ 0';
I've encountered a couple of problems with the program that i'm writing now.
- strstr outputs my substring only if it's at the end of my string enter image description here
- it also outputs some trash characters after that enter image description here
- I've had problems with "const char *haystack" and then adding input to it, so i did it with fgets and getchar loop
- somewhere along the way it worked with a substring that was not only at the end, but then i outputted substring and the rest of the string ater that
here is my main:
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);
}
and my function:
int wordInString(const char *str, const char * wd)
{
char *ret;
ret = strstr(str,wd);
printf("The substring is: %s\n", ret);
return 0;
}
You read one string with fgets()
and the other with getchar()
upto the end of file. There is a trailing '\n'
at the end of both strings, Hence strstr()
can only match the substring if it is at the end of the main string.
Furthermore, you do not store a final '\0'
at the end of haystack
. You must do this because haystack
is a local array (automatic storage), and as such is not initialized implicitly.
You can correct the problem this way:
//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';
这篇关于作品的strstr只有当我子是字符串的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!