栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++: 参数解析

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++: 参数解析

在 C++中我们有时候需要对含有空白符的字符串进行参数解析(Tokenize), 将字符串分解为若干个不含空格的字符串(token).下面介绍两种C++ 中参数解析的方法.

使用 stringstream

使用输入流对象(istream)的输入运算符>>输入含空格的字符串时, 字符串变量只能获取到空格前的部分. 利用该特性, 我们可以用来实现参数解析. 代码如下:

std::vector parse1(const std::string &line)
{
    std::stringstream ss(line);
    std::vector args;
    while(!ss.eof())
    {
        std::string arg;
        ss >> arg;
        args.push_back(arg);
    }
    return args;
}
使用 string::find_first_(not_)of

使用 string::find_first_of()函数 和 string::find_first_not_of()函数同样可以实现参数解析. string::find_first_not_of() 用于查找非空白符所在位置, string::find_first_of()用于查找空白符所在位置, 使用string::substr() 提取子字符串. 代码如下:

std::vector parse2(const std::string &line)
{
    std::vector args;
    const char* delim = " t";
    size_t sp = 0;
    size_t ep = 0;
    while (ep != std::string::npos)
    {
        sp = line.find_first_not_of(delim, ep);
        ep = line.find_first_of(delim, sp);
        args.push_back(line.substr(sp, ep-sp));
    }
    return args;
}
示例代码

示例代码如下:

// main.cpp

#include 
#include 
#include 

std::vector parse1(const std::string &line)
{
    std::stringstream ss(line);
    std::vector args;
    while(!ss.eof())
    {
        std::string arg;
        ss >> arg;
        args.push_back(arg);
    }
    return args;
}

std::vector parse2(const std::string &line)
{
    std::vector args;
    const char* delim = " t";
    size_t sp = 0;
    size_t ep = 0;
    while (ep != std::string::npos)
    {
        sp = line.find_first_not_of(delim, ep);
        ep = line.find_first_of(delim, sp);
        args.push_back(line.substr(sp, ep-sp));
    }
    return args;
}

int main(int, char**) {
    std::cout << ">";
    std::string line;
    std::getline(std::cin, line);
    std::vector args = parse2(line);
    std::cout << "parse 1:" << std::endl;
    for (auto &&arg : args)
    {
        std::cout << "t" << arg << std::endl;
    }
    std::vector args2 = parse2(line);
    std::cout << "parse 2:" << std::endl;
    for (auto &&arg : args2)
    {
        std::cout << "t" << arg << std::endl;
    }
    return 0;
}

以下是测试结果:

如果你有更好的方法, 欢迎评论区留言分享.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/950466.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号