user1871869
user1871869

Reputation: 3367

Binary Search with character arrays?

I'm having a little bit of trouble understanding how to do a binary search with strings. What I have as input is a sentence in the command line prompt which is argv[1], (argv[0] being the name of the executable I output). This is how it looks:

./a.out "This is my sentence."

And included in my file is also a .h file that holds two arrays--a nouns array that holds certain set of nouns and a verbs array that holds a certain set of verbs. What I want to do is simply check if the verbs and nouns in argv[1] are in the nouns or verbs array, and I want to print them out. However, I'm having trouble understanding how to parse each word out of the sentence as shown above and comparing them to the verbs or nouns array as there are no strings in C (as opposed to C++). Could anyone provide an algorithm/psuedocode or an idea on how to do so? If so that would be very much appreciated!

Upvotes: 1

Views: 2827

Answers (2)

Nobilis
Nobilis

Reputation: 7448

Yes, as it's been mentioned, the nouns and verbs arrays need to be sorted for this to work. strcmp() will return -1 (or less), 0 or 1 (or more) depending on whether the left argument is smaller, equal or bigger than the right one.

Couldn't think of a better place for an algorithm than Wikipedia, it's even written in C. Of course you would need to adapt it for your purposes a little bit.

Good luck.

Upvotes: 1

mclaassen
mclaassen

Reputation: 5128

Strings in C are arrays of characters terminated with a NULL (byte value 0) character.

You can use char[] or char* to refer to a "string".

Loop using a pointer to the input string which is incremented each time. While the character is not a space add it to some buffer. If the character is a space, add a NULL to the buffer (C strings are null terminated) and use the buffer as input to the binary search algorithm, which will use strcmp to compare the strings. Clear the buffer and repeat until you find NULL character.

Here is some code that will parse the input into words:

int main(int argc, char* argv[])
{
    char *p = argv[1];
    char buffer[100]; //assuming no words > 100 characters

    int count = 0;

    while(buffer[count++] = *p++)
    {
        if(*p == ' ' || *p == 0)
        {
            buffer[count] = 0;
            printf("Word: %s\n", buffer);

            //do something with buffer

            for(int i=0; i<count; i++) //clear the buffer
                buffer[i] = 0;
            count = 0;
        }
    }

    return 0;
}

Upvotes: 2

Related Questions