简体   繁体   English

在C中进行字符串数组搜索

[英]String array searching in C

I'm trying to figure out how to search a list of names that are inputted into a string array. 我试图弄清楚如何搜索输入到字符串数组中的名称列表。 If the name entered is part of the original array, then the search function should return the position of the string in the array; 如果输入的名称是原始数组的一部分,则搜索功能应返回字符串在数组中的位置;否则,返回0。 if the string is not found, it should return -1. 如果找不到该字符串,则应返回-1。 If -1 is returned then I want to be able to print out "not found", which doesn't seem like it would be too hard to figure out, but if the name is found, I want to be able to print out the position at which the name is found. 如果返回-1,那么我希望能够打印出“未发现”,这似乎并不像它会是太难搞清楚,但如果找到该名字,我希望能够打印出找到名称的位置。

Here is my code, obviously I'm new to this, so I might have butchered how this is supposed to be done. 这是我的代码,很显然,我是新手,所以我可能已经怀疑应该怎么做。 The rest of my code seems to work fine, but it's this function that has me at a loss. 我的代码其余部分似乎都可以正常工作,但是正是这个功能让我不知所措。

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

#define MAX_NAMELENGTH 10
#define MAX_NAMES 5
void initialize(char names[MAX_NAMES][MAX_NAMELENGTH]);
int search(char names[MAX_NAMES][MAX_NAMELENGTH],int i,Number_entrys);
int main()
{
    char names[MAX_NAMES][MAX_NAMELENGTH];
    int i;
    initialize(names);
    search(names,i,Number_entrys);
    search_result= search(names,i,Number_entrys);
    if (search_result==-1){
        printf("Found no names.\n");
    }
    if(search_result==0){
       printf("Name found");
    }    getch();
    return 0;
}

void initialize(char names[MAX_NAMES][MAX_NAMELENGTH])
{
    int i, Number_entrys;

    printf("How many names would you like to enter to the list?\n");
    scanf("%d",&Number_entrys);

    if(Number_entrys>MAX_NAMES){
               printf("Please choose a smaller entry\n");
    }else{
        for (i=0; i<Number_entrys;i++){
            scanf("%s",names[i]);
        }
    }
    for(i=0;i<Number_entrys;i++){

        printf("%s\n",names[i]); 
    }
}

int search(char names[MAX_NAMES][MAX_NAMELENGTH],int i)
{
    int j, idx;
    char name[MAX_NAMELENGTH];
    printf("Now enter a name in which you would like to search the list for:");
    scanf("%s", name);

    for(x = 0; x < Number_entrys; x++) {
        if ( strcmp( new_name, names[x] ) == 0 ){
            /* match, x is the index */
            return x;
        }else{
            return -1;   
        }
    }
}

You means like this: 您的意思是这样的:

int search(char names[MAX_NAMES][MAX_NAMELENGTH], int i)
{
     int j, idx;
     char name[MAX_NAMELENGTH];
     printf("Now enter a name in which you would like to search the list for:");
     scanf("%s", name);

     idx = -1;
     for(j = 0; j < i; j++){
         if(strstr(names[i], name) != NULL){
             idx = j;break;
         }
     }
     return idx;
}

There are several problems here. 这里有几个问题。

The purpose of search is to ask the user to enter a single name to be searched for. 搜索的目的是要求用户输入要搜索的单个名称。 So why is 那为什么

 char new_name[MAX_NAMES][MAX_NAMELENGTH];

You need only a single array 您只需要一个数组

 char new_name[MAX_NAMELENGTH];

Then you have a loop you just go round once, so you don't need a loop 然后有一个循环,您只需循环一次,所以您不需要循环

 scanf("%s",new_name);

would be enough. 足够了。 This feels like you have copied the code you used to fill your array of names, but haven't really understood its essence. 感觉就像您已经复制了用于填充名称数组的代码,但是并没有真正理解其本质。

Another problem is that you have no control on how long a name the user might enter. 另一个问题是您无法控制用户输入名称的时间。 What would happen if the user typed a very long name? 如果用户键入一个很长的名字会发生什么? You'd over-fill the array and your program will probably crash and burn. 您将过度填充阵列,程序可能会崩溃并刻录。 Read this article to learn about how to control this. 阅读本文以了解如何控制它。

To be really pedantic you should also check the return code from scanf, you are expecting to read one item so the return value should be 1, anything else would be an error. 要真正学究,还应该检查scanf的返回码,因为您希望读取一个项目,所以返回值应该为1,否则其他任何操作都会出错。

Then you are trying to use strstr(), to look through an array of char arrays. 然后,您尝试使用strstr()遍历char数组。 The strstr documentation says that its purpose is to search for a substring within a string rather than search through an array of strings. strstr 文档说,其目的是在字符串中搜索子字符串,而不是在字符串数组中搜索。

So instead just search the array by hand 因此,只需手动搜索数组

/* what is i? the number of items used in the array? */
for(x = 0; x < i; x++) {
    if ( strcmp( new_name, names[x] ) == 0 ){
        /* match, x is the index */
        return x;
    }
}
/* here with no match */
return -1;

In your main 在你的主

int search_result; int search_result;

search_result = search( /* etc */ );

if ( search_result == -1 ) {
     /* print "not found" here */
} else {
     /* print something else */
}

(8) ... (8)...
Maybe we'll turn it all around 也许我们会扭转一切
'Cause it's not too late 因为现在还不算太晚
It's never too late!! 永远不会太迟!! (8) (8)
:) ! :)!


Sorry about the song ^_^... oh Well, I was having fun with this question for a couples of minutes, I hope this code help you out a little more, with regards: 抱歉,这首歌^ _ ^ ...哦,我在这个问题上玩了几分钟,希望这段代码可以帮助您,在以下方面有所帮助:

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


/* return array of indexs */

int*
search(const char *list, size_t slen, const char **arr_names, size_t arrlen)
{
    int *arr_idx;
    int j,i,idx;

    i=idx=0;

    arr_idx = malloc(sizeof(int)*arrlen+1);

    if(!arr_idx)
        exit(EXIT_FAILURE);

    for(i=0; i<slen; i++) {
        for(j=0; j<arrlen ; j++) {
            if(!strncmp(&list[i], &arr_names[j][0], strlen(arr_names[j]))) {
                arr_idx[idx] = j;
                idx++;
            }
        }
    }

    arr_idx[idx] = -1; /* -1 terminated array */
    if(!idx) {
        free(arr_idx);
        return NULL; /* found no names */
    }

   return arr_idx;
}
/* I'm a sick [something], nul terminated strings :P */
const char *string   = "My favorite artists: ATB, Nujabes and Bonobo also Aphex Twins is nice, along with Trapt and Breaking Benjamin.\0";
const char *names[] = {"ATB\0", "Scifer\0", "Aphex\0", "Bonobo\0", "Nujabes\0", "Tipper\0"};
#define N_NAMES 6

int
main(void)
{
    int i;
    int *array;

    array = search(string, strlen(&string[0]), names, N_NAMES);

    if(!array) {
        puts("Found no names.\n");
        return EXIT_SUCCESS;
    }

    printf("Names found: ");
    for(i=0; array[i]!=-1; i++)
        printf("%s,", names[array[i]]);

    printf("\b \n");
    free(array);  /* important */
    /* system("pause"); */   /* NOTE: decomment this if you're on windows */
   return EXIT_SUCCESS;
}

ran some tests: 运行了一些测试:

~$ ./program


output 输出
Names found: ATB,Nujabes,Bonobo,Aphex

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

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