2013-06-26 28 views
0

如何搜索2d字符串數組中的整個單詞。 此代碼僅輸出我輸入的單詞的第一個字母。如何在C編程中搜索2d字符串數組中的單詞

任何人都可以幫助我嗎?

那麼這個索引是如何在一個函數中傳遞的,只是我在這個搜索中找到的索引。

#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; 
} 

回答

1

您需要使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; 
} 
+0

這就是它的好友,非常感謝。現在 ,你知道如何僅此指數進入一個功能: 像我有一些值: '得分[PEOPLE] = {23,12,45,12};' 和我創建了一個函數,其中我發現最小的,然後我只想顯示我找到的這個索引(來自搜索)的分數和該人的位置。 你有什麼想法可以幫助我 謝謝,欣賞它 – user2512806

+0

'int smallest(int a [],int n){int i,m = a [0];對於(i = 1; i ctn

0

Found_name只是一個字符,當它應該是一個字符*與正確的空間量。所以如果你輸入「查找這個字符串」,你怎麼能將該字符串存儲到1個字節的位置?

相關問題