简体   繁体   English

更好地了解C中的strstr

[英]Better understanding of strstr in C

I already asked on question earlier about the string function strstr, and it just turned out that I had made a stupid mistake. 前面我已经问过有关字符串函数strstr的问题,事实证明我犯了一个愚蠢的错误。 Now again i'm getting unexpected results and can't understand why this is. 现在我又得到了意想不到的结果,无法理解为什么会这样。 The code i've written is just a simple test code so that I can understand it better, which takes a text file with a list of 11 words and i'm trying to find where the first word is found within the rest of the words. 我编写的代码只是一个简单的测试代码,因此我可以更好地理解它,它使用一个包含11个单词的列表的文本文件,并且我试图查找在其余单词中找到第一个单词的位置。 All i've done is move the text document words into a 2D array of strings, and picked a few out that I know should return a correct value but are instead returning NULL. 我所要做的就是将文本文档中的单词移动到2D字符串数组中,并挑选出一些我知道应该返回正确值但返回NULL的值。 The first use of strstr returns the correct value but the last 3, which I know include the word chant inside of them, return NULL. 第一次使用strstr返回正确的值,但最后3个(我知道其中包含单词chant)返回NULL。 If again this is just a stupid mistake I have made I apologize, but any help here on understanding this string function would be great. 如果这只是一个愚蠢的错误,我已经向我道歉了,但是在理解此字符串函数方面的任何帮助都会很棒。

The text file goes is formatted like this: 文本文件go的格式如下:

chant  
enchant    
enchanted    
hello    
enchanter    
enchanting    
house    
enchantment    
enchantress    
truck    
enchants

And the Code i've written is: 我写的代码是:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {

FILE* file1;
char **array;
int i;
char string[12];
char *ptr;

array=(char **)malloc(11*sizeof(char*));

for (i=0;i<11;i++) {
    array[i]=(char *)malloc(12*sizeof(char));
}

file1=fopen(argv[1],"r");

for (i=0;i<11;i++) {
    fgets(string,12,file1);
    strcpy(array[i],string);
}

ptr=strstr(array[1],array[0]);
printf("\nThe two strings chant and %s yield %s",array[1],ptr);
ptr=strstr(array[2],array[0]);
printf("\nThe two strings chant and %s yield %s",array[2],ptr);
ptr=strstr(array[4],array[0]);
printf("\nThe two strings chant and %s yield %s",array[4],ptr);
ptr=strstr(array[5],array[0]);
printf("\nThe two strings chant and %s yields %s",array[5],ptr);


return 0;
}

Get rid of the trailing \\n after fgets() . 摆脱fgets()之后的\\n

for (i=0;i<11;i++) {
    fgets(string, sizeof string, file1);
    size_t len = strlen(string);
    if (len > 0 && string[len-1] == '\n') string[--len] = '\0';
    strcpy(array[i], string);
}
char *chomp(char *str){
    char *p = strchr(str, '\n');
    if(p)
        *p = '\0';
    return str;
}
...
strcpy(array[i], chomp(string));

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

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