注意其中有空格。
我可以使用哪种功能?
答案 0 :(得分:5)
您可以使用
if (!strncmp("GET ", str, 4)
{
...
}
else if (!strncmp("POST ", str, 5))
{
...
}
else
{
...
}
答案 1 :(得分:3)
当您只需要区分几个字符串时, 不能使用strncmp()
:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
static uint32_t method_hash(const char *key)
{
int len;
uint32_t hash;
int i;
len = strlen(key);
for (hash = 0, i = 0; i < len; i++) {
hash += (unsigned int) key[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("Usage: %s <method>\n", argv[0]);
return 0;
}
switch(method_hash(argv[1])) {
case 802187597:
printf("Its GET\n");
break;
case 740659500:
printf("Its POST\n");
break;
default:
printf("Its RUBBISH\n");
return 1;
}
return 0;
}
请注意,哈希不是防冲突,但适合了解GET和POST之间的区别。我经常在词典中使用那个小宝石,当我想我有匹配时只调用strncmp()
。
我发布这个答案告诉你,有很多方法可以处理字符串,希望你在继续学习C时避免看起来像这样的代码:
if (! strncmp(string, "FOO ", 4)) {
do_this();
} else if (! strncmp(string, "BAR ", 4)) {
do_that();
} else if (! strncmp(string, "FOOBAR ", 7)) {
do_both();
/* ... madness ensues through 200 more lines and 100 more else if's ... */
} else {
return 0;
}
我的例子并不恰当。如果希望代码可移植,则需要在运行时确定哈希值,而不是仅插入已知值。这是读者的练习(提示,切换案例需要常量)。
答案 2 :(得分:1)
将strncmp与参数string1,string2,n一起使用,其中string1和string2是要比较的字符串,n是字符数。如果字符串匹配,则strncmp返回0;如果字符串字典小于string2,则strncmp返回0;如果string2小于string1,则strncmp返回&lt; 0例子:
#include <string.h>
...
strncmp(somestring, "GET ", 4) == 0
strncmp(somestring, "POST ", 5) == 0
答案 3 :(得分:1)
#include <stdio.h>
#include <string.h>
typedef enum httpmethod
{
HTTP_ERR,
HTTP_GET,
HTTP_POST,
HTTP_METHOD_COUNT
} httpmethod;
const char* http_method_str[HTTP_METHOD_COUNT + 1] =
{
"UNKNOWN",
"GET ",
"POST ",
0
};
httpmethod str_get_http_method(const char* str)
{
if (!str || strlen(str) < 4)
return HTTP_ERR;
const char* ptr[HTTP_METHOD_COUNT];
int i;
int failcount = 0;
for (i = 1; i < HTTP_METHOD_COUNT; ++i)
ptr[i] = http_method_str[i];
while (*str != '\0' && failcount < HTTP_METHOD_COUNT - 1)
{
for (i = 1; i < HTTP_METHOD_COUNT; ++i)
{
if (ptr[i] && *str != *ptr[i]++)
{
ptr[i] = 0;
++failcount;
}
}
str++;
}
for (i = 1; i < HTTP_METHOD_COUNT; ++i)
if (ptr[i])
return i;
return HTTP_ERR;
}
int main(int argc, char** argv)
{
const char* test[4] = { "GET ", "POST ", "GIT ", "PAST " };
httpmethod result = HTTP_ERR;
int i;
for (i = 0; i < 4; ++i)
{
printf("checking str: %s\n", test[i]);
result = str_get_http_method(test[i]);
printf("result is type: %s\n", http_method_str[result]);
}
return 0;
}