Search code examples
ccstringstrcmp

Scan an array using strcmp


I'm wondering if there's a way you can scan an array for a match using strcmp. I know the parameters passed to strcmp are C strings. So something like this wouldn't work:

strcmp(arrayofstrings[x], c-string)

Solution

  • If you're trying to search the entire array, rather than just comparing two elements, you will need a loop.

    const int N = 10;
    const char * desired = "desiredString";
    char * arrayOfStrings[N];
    
    // You should initialize the elements
    // in arrayOfStrings[] before searching
    
    // Searching an unsorted array is O(N)
    for(i = 0; i < N; i++)
    {
        if(strcmp(arrayOfStrings[i], desired) == 0)
        {
            printf("Found %s.", desired);
            break;
        }
    }