在C中搜索char字符串数组中的字符串

时间:2015-11-28 21:39:15

标签: c arrays string search char

char names [MAX_CLASS_SIZE][MAX_NAME_SIZE+1]={"Julias Hoffman","Dianne Conner","Mitchell Cooper","Johnnie Greene","Johanna Mason","Kevin Adkins","Brandi Spencer","Marian Tyler","Chester Cross","Martin Lawrence","Jane Smith","Sara Jones"};

char specificName[]="";

int search(char names[][MAX_NAME_SIZE+1],char specificName[])

for(i=0;i<MAX_CLASS_SIZE;i++){
    if (strcmp(names[i],specificName)==0)
    {
        printf("Found %s",names[i]);
        return i;
    }
}

此函数接收一个名为name和a的字符串数组 表示特定名称的字符数组。这个 函数在数组名称中搜索特定名称 如果找到,则返回特定名称的索引,如果是,则返回-1 它找不到。

无法让数组正确格式化我的道歉。在main中,我向用户询问名称并将其存储在specificName char数组中。然后在搜索功能中,我试图搜索给定名称的用户的名称数组,并根据是否找到名称返回特定值。我已经包含了必要的库。我试图使用strcmp这样做,但似乎没有正常工作。非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

快速看一下它似乎工作正常。您的i需要声明为int,否则,以下工作:

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

#define MAX_CLASS_SIZE 100
#define MAX_NAME_SIZE 100

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

    char names [MAX_CLASS_SIZE][MAX_NAME_SIZE+1]={"Julias Hoffman","Dianne Conner","Mitchell Cooper","Johnnie Greene","Johanna Mason","Kevin Adkins","Brandi Spencer","Marian Tyler","Chester Cross","Martin Lawrence","Jane Smith","Sara Jones"};
    char specificName[]="Brandi Spencer";
    int search(char names[][MAX_NAME_SIZE+1],char specificName[]);
    for(int i=0;i<MAX_CLASS_SIZE;i++){
        if (strcmp(names[i],specificName)==0){
            printf("Found %s",names[i]);
            return i;
        }
    }

    return 0;
}

输出

找到Brandi Spencer

我的猜测是你没有正确传递用户输入。检查strcmp()之前的specificName []。

答案 1 :(得分:0)

您可以尝试以下方法:

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

int search(char **names,char *specificName, size_t length){
    size_t i,found=0;
    for(i=0;i<length;i++){
        if (strcmp(*(names + i),specificName)==0){
            found = 1;
        }
    }
    return found == 1 ? 0 : 1;
}


int main(void) {
    size_t length;
    char specificName[100];
    char *names[12]={"Julias Hoffman","Dianne Conner","Mitchell Cooper","Johnnie Greene",
                     "Johanna Mason","Kevin Adkins","Brandi Spencer","Marian Tyler",
                     "Chester Cross","Martin Lawrence","Jane Smith","Sara Jones"};

    length = sizeof names / sizeof *(names + 0);

    printf("Type a name to be searched:> ");
    if( fgets (specificName, 100, stdin) == NULL){
        printf("Error!\n");
    }

    specificName[strcspn(specificName, "\n")] = 0;

    if((search(names,specificName,length)) == 0){
        printf("Found %s",specificName);
    }else{
        printf("There was no Record Found.\n");
    }
    return 0;
}

输出:

Type a name to be searched:> Sara Jones
Found Sara Jones