与字符数组二进制搜索? [英] Binary Search with character arrays?

查看:174
本文介绍了与字符数组二进制搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有麻烦了解如何做字符串二进制搜索一点点。我有什么作为输入是在命令行提示符下一句是ARGV [1],(的argv [0]为可执行的I输出的名称)。这是它的外观:

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."

和包含在我的文件也是一个拥有两个数组.h文件 - 一个名词数组保存某一套名词和保存一组特定的动词的动词数组。我想要做的是简单的检查,如果argv中[1]动词和名词是名词或动词阵中,我想打印出来。不过,我无法理解如何解析每一个字出来的句子,如上图所示,并将其比作动词或名词阵列,因为在C字符串没有(相对于C ++)。谁能提供一个算法/伪code或对如何做到这一点的想法?如果是这样,这将是非常美联社preciated!

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!

推荐答案

在C字符串是一个NULL结尾的字符数组(字节值0)字符。

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

您可以使用的char []或字符*指一个串。

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

循环使用指针向其中每次递增输入字符串。而字符不是空格它添加到一些缓冲。如果字符是一个空间,一个NULL添加到缓冲区(C字符串是空终止),并使用缓冲输入到二进制搜索算法,它使用的strcmp比较字符串。清除缓存并重复,直到你找到空字符。

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.

下面是一些code,将解析输入文字:

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

这篇关于与字符数组二进制搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆