簡體   English   中英

如何在C編程中搜索2D字符串數組中的單詞

[英]How to search a word in a 2d string array in C programming

如何在二維字符串數組中搜索整個單詞。 此代碼僅向我輸出輸入的單詞的第一個字母。

誰能幫我這個 ?

那個索引是如何僅通過我從這個搜索中找到的索引傳入函數的。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#define PEOPLE 4
#define LEN_NAME 30

int main (void)
{
    int i;
    char found_name;
    char name[PEOPLE][LEN_NAME]= {"John Lucas","Armanod Jonas",
                                "Jack Richard","Donovan Truck"};

    printf("What name do you want to search?\n>");
    scanf("\n%s", &found_name);
    for (i = 0 ; i < PEOPLE; i ++)
    {
        if (strchr(name[i], found_name ) != NULL)
        {
            printf( "Found %c in position %d,%s\n", found_name, i+1, name[i]);
            printf( " index of player is %d.\n",i +1);
        }
    }
    return 0;
}

您需要將found_name設為一個char數組,而不是char。 另外,您需要使用strstr(搜索字符串)而不是strchr(搜索單個字符)進行搜索。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#define PEOPLE 4
#define LEN_NAME 30
int main(void)
{
    int i;
    char found_name[LEN_NAME];
    char name[PEOPLE][LEN_NAME] = { "John Lucas", "Armanod Jonas",
    "Jack Richard", "Donovan Truck"
    };

    printf("What name do you want to search?\n>");
    scanf("%29s", found_name);
    for (i = 0; i < PEOPLE; i++) {
    if (strstr(name[i], found_name) != NULL) {
        printf("Found %c in position %d,%s\n", found_name, i + 1,
           name[i]);
        printf(" index of player is %d.\n", i + 1);
    }
    }
    return 0;
}

Found_name僅應是一個字符,並且應具有適當的空格數*。 因此,如果您鍵入“查找此字符串”,則如何將該字符串存儲到1個字節的位置?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM