C++, boost : which is fastest way to parse string like tcp://adr:port/into address string and one int for port?

标签 c++ string boost tcp

我们有 std::string Atcp://adr:port/ 如何将它解析为地址 std::string 和一个用于端口的 int?

最佳答案

虽然有些人不认为它特别适合 C++,但最简单的方法可能是使用 sscanf:

sscanf(A.c_str(), "tcp://%[^:]:%d", &addr, &port);

另一种可能性是将字符串放入字符串流中,为流注入(inject)一个将大多数字母和标点符号视为空格的方面,然后像这样读取地址和端口:

std::istringstream buffer(A);
buffer.imbue(new numeric_only);
buffer >> addr >> port;

切面看起来像这样:

struct digits_only: std::ctype<char> 
{
    digits_only(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table()
    {
        // everything is white-space:
        static std::vector<std::ctype_base::mask> 
            rc(std::ctype<char>::table_size,std::ctype_base::space);

        // except digits, which are digits
        std::fill(&rc['0'], &rc['9'], std::ctype_base::digit);

        // and '.', which we'll call punctuation:
        rc['.'] = std::ctype_base::punct;
        return &rc[0];
    }
};

operator>> 将空格视为“字段”之间的分隔符,因此这会将类似 192.168.1.1:25 的内容视为两个字符串:“192.168.1.1”和“25”。

关于C++, boost : which is fastest way to parse string like tcp://adr:port/into address string and one int for port?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4210567/

相关文章:

c++ - 与重置的计数器相比

ruby-on-rails - Ruby .split() 正则表达式

c++ - boost 链接器错误错误的工具集

c++ - 使用 Boost.Date_Time 解析带时区的日期时间?

c++ - 为什么它在不同的 ide online 中有不同的行为

c++ - 如何使用 OpenGL 和 QT?

c# - C# 应用程序中的 C++ lib RTTI

python - 检查字符串是否包含python中的数字/数字/数字

android - 将字符串数组传递给另一个 Activity

c++ - 为深度优先搜索定义 ColorMap 的最简单方法