【问题标题】:How can I search a part of a string and display it?如何搜索字符串的一部分并显示它?
【发布时间】:2021-09-14 10:36:22
【问题描述】:

我在这里有这段代码来搜索文件中的字符串并显示它。我如何编辑这段代码,以便只搜索该字符串的一部分? 比如说,该文件包含作者“dennis zill”,如果我搜索“zill”,我希望代码显示“dennis zill”。

int searchauthor(FILE *ptr)    //searching starts
    {
        int save;
        char de;
        char in_name[30];
        int flag = 1;
    
        save = readbooks();
        ptr = fopen("books info.txt", "r");
        fflush(stdin);
        printf("\n Enter the name of the author: ");
        gets(in_name);
        printf("-------------------------------------------------");
    
        for(int i = 0; i < save; i++){
            if(strcmpi(in_name, info[i].bauthor) == 0){
                printf("\n Book name: %s\n Price: %u\n Number of books available: %u\n Number of pages: %u\n-------------------------------------------------", info[i].bname, info[i].price, info[i].numavail, info[i].bpages);
                flag = 0;
            }
        }
    
        if (flag == 1){
            printf("\n Not found.\n Do you want to try another search [Y/N]? ");
            scanf("%c", &de);
            if(de == 'y' || de == 'Y'){
                system("cls");
                in_name[MAX] = reset(in_name);
                fclose(ptr);
                return 2;
            }
            else if(de == 'n' || de == 'N'){
                printf("\n You will be redirected to main menu");
                for(int k = 1; k <= 5; k++){
                    Sleep(300);
                    printf(".");
                }
                system("cls");
                return 1;
            }
        }
    
        printf("\n\n Do you want to try another search [Y/N]? ");
        scanf("%c", &de);
    
        if (de == 'y' || de == 'Y') {
            system("cls");
            in_name[MAX] = reset(in_name);
            return 2;       //return 2 to case 3 to search again
        }
        else if (de == 'n' || de == 'N') {
            system("cls");
            printf("\n You will be redirected to main menu");
            for(int k = 1; k <= 5; k++){
                Sleep(300);
                printf(".");
            }
            system("cls");
            return 1;
        }
    }  //searching ends

【问题讨论】:

  • 尝试使用strstr()strcasestr() 而不是strcmp()
  • 请将纯文本添加为​​文本,而不是屏幕截图。
  • @tstanisl 如果我使用 strstr() 它只会显示文件中的所有内容!!
  • @AliElneklawy,你试过strstr(info[i].bauthor, in_name) != NULL 吗?
  • @tstanisl 完成。有用!我可以让它不区分大小写吗?

标签: c string


【解决方案1】:

问题出在这条线:

if(strcmp(in_name, info[i].bauthor) == 0){

只有在完全匹配时才会成功。

而不是使用strcmp 使用strstr(或其不区分大小写的变体strcasestr(),如果可用)。

char *strstr(const char *haystack, const char *needle);

haystack 是作者的全名,needle 是用户的输入。 函数在失败时返回NULL,因此检查是否返回了非NULL就足够了。

if(strstr(info[i].bauthor, in_name) != NULL){

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    相关资源
    最近更新 更多