提取URL中的ip,端口,路径,协议

#include <iostream>
#include <string>
#include <cassert>

// 提取 URL 中的 IP 地址、端口号和路径
bool parseUrl(const std::string& url, std::string& scheme, std::string& host, std::string& port, std::string& path) {
    size_t schemeEnd = url.find("://");
    size_t atSign = url.find("@"); // 寻找可能存在的 @ 符号,用于区分用户名密码和主机名
    size_t slashAfterScheme = url.find('/', schemeEnd + 3);

    // 提取 scheme
    if (schemeEnd == std::string::npos) {
        return false;
    }
    scheme = url.substr(0, schemeEnd);

    // 提取 host 和 port
    size_t colonPos = url.find(':', atSign == std::string::npos ? schemeEnd + 3 : atSign + 1);
    if (colonPos == std::string::npos) {
        host = url.substr(schemeEnd + 3, slashAfterScheme - (schemeEnd + 3));
    } else {
        host = url.substr(schemeEnd + 3, colonPos - (schemeEnd + 3));
        port = url.substr(colonPos + 1, slashAfterScheme - (colonPos + 1));
    }

    // 提取 path
    if (slashAfterScheme == std::string::npos) {
        path.clear();
    } else {
        path = url.substr(slashAfterScheme);
    }

    // 成功解析
    return true;
}

int main() {
    std::string url = "http://192.168.0.188:8088/svr/api/pub/auto";

    std::string scheme, host, port, path;

    bool success = parseUrl(url, scheme, host, port, path);

    if (success) {
        std::cout << "Scheme: " << scheme << std::endl;
        std::cout << "Host: " << host << std::endl;
        std::cout << "Port: " << port << std::endl;
        std::cout << "Path: " << path << std::endl;

        // 断言检查 http://192.168.0.188:8088/svr/api/pub/auto
        assert(scheme == "http");
        assert(host == "192.168.0.188");
        assert(port == "8088");
        assert(path == "/svr/api/pub/auto");
    } else {
        std::cout << "Failed to parse URL." << std::endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值