C - 将char数组与字符串进行比较

时间:2016-06-16 12:36:15

标签: c string compare strcmp

我有一个套接字服务器应该收到一条消息并写一个答案。对于某些消息,我想发送一个特殊答案。如果消息是例如“你好”我想回答“嗨!”。这是我的代码的一部分:

...
char in[2000];
char out[2000];
...
while((read_size = recv(fd, in, 2000, 0)) > 0){

    if(strcmp(in, "Hello") == 0){

        strcpy(out, "Hi!\n");

    }
    else{

        strcpy(out, in);

    }

    write(fd, out, strlen(out));

}
...

但strcmp()在这里不行。因为当我输入“Hello”时,“in”变量中不仅有“Hello”,因为长度是2000.但是,如果收到的消息是“Hello”,我现在如何检查?

1 个答案:

答案 0 :(得分:2)

使用 strncmp 函数,该函数比较字符串的第一个 n 字节:

// paging and feeds
if ( get_query_var('paged') || is_feed() || get_query_var('cpage') ) {
    while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] ) || preg_match( '#/(comments/?)?(rss|rdf|atom|rss2)(/+)?$#', $redirect['path'] ) || preg_match( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?$#", $redirect['path'] ) ) {
        // Strip off paging and feed
        $redirect['path'] = preg_replace("#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path']); // strip off any existing paging
        $redirect['path'] = preg_replace('#/(comments/?)?(rss2?|rdf|atom)(/+|$)#', '/', $redirect['path']); // strip off feed endings
        $redirect['path'] = preg_replace("#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?$#", '/', $redirect['path']); // strip off any existing comment paging
    }

    //more code

}