C获取字符串中的一部分字符串

标签 c string substring

我正在尝试编写解析 HTTP GET 请求并检查“主机”是否为 www.bbc.co.uk 的代码。

这是我的工作代码:

char data[] = "GET /news/ HTTP/1.1\nHost: www.bbc.co.uk\nConnection: keep-alive";
    unsigned int size = strlen(data);

    if (size>3 && data[0] == 'G' && data[1] == 'E' && data[2] == 'T'){ //If GET Request
        int host_index = -1;

        for (int i=4; i<size-4; i++){
            if (data[i] == 'H' && data[i+1] == 'o' && data[i+2] == 's' && data[i+3] == 't'
                    && data[i+4] == ':' && data[i+5] == ' '){
                host_index = i+6;
            }
        }

        if ( host_index != -1 && size > host_index+11 &&
                data[host_index] == 'w' && data[host_index+1] == 'w' && data[host_index+2] == 'w' &&
                data[host_index+3] == '.' && data[host_index+4] == 'b' && data[host_index+5] == 'b' &&
                data[host_index+6] == 'c' && data[host_index+7] == '.' && data[host_index+8] == 'c' &&
                data[host_index+9] == 'o' && data[host_index+10] == '.' && data[host_index+11] == 'u' &&
                data[host_index+12] == 'k')
        {
            printf("BBC WEBSITE!\n");
        }

    }

我认为这是很多代码而不是很多。我怎样才能使这段代码更紧凑?

[请保持纯 C。没有第 3 方库]

非常感谢!

最佳答案

为什么不使用 strstr() ?

使用 strstr() 将大字符串拆分成 block ,然后通过单独的例程解析较小的 block

关于C获取字符串中的一部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27301956/

相关文章:

c - "complex"宏如何修改C中的 "double"和 "float"类型?

C++ 将数据从 std::string 复制到 std::wstring

java - java中字符串的字体设置

python - 读取文本文件并添加子字符串(python)

c - 在c中不显示字符链表

java - 返回到嵌入 Java VM 的程序的 JNI 本地引用的规则是什么?

c - DSNAME 长度无效的 IBM Window Services (DWS) CSRIDAC

Java-如何在字符串中查找非字母字母? (快速方法)

java - 我需要从 java 字符串 Tokenizer 中获取一个子字符串

c - 在 char[] 中查找带有通配符的子字符串