微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在c ++中获取字符串的特定部分?

如何解决如何在c ++中获取字符串的特定部分?

我有以下字符串,我需要取出 id (68890) 类似日期 (01/14/2005)

CString strsample = "This is demo to capture the details of date (01/14/2005) parent id (68890) read (0)"  

CString strsample =   This is demo (Sample,Application) to capture the details of date (01/14/2005) parent id (68890) read (0) Total(%5)

我如何在 C++ 中实现这一点,有没有办法在正则表达式或任何可用的函数中做到这一点。

解决方法

使用标准库的最简单方法是使用 std::sscanf:

#include <iostream>
#include <string>
#include <cstdio>
#include <ctime>
#include <iomanip>

int main()
{
    std::string s;

    while (std::getline(std::cin,s)) {
        std::tm t{};
        int id,read;
        auto c = std::sscanf(s.c_str(),"This is demo to capture the details of date (%d/%d/%d) parent id (%d) read (%d)",&t.tm_mon,&t.tm_mday,&t.tm_year,&id,&read);

        --t.tm_mon;
        t.tm_year -= 1900;

        std::mktime(&t);
        if (c == 5) {
            std::cout << std::put_time(&t,"%F") 
                << " id: " << id 
                << " read: " << read
                << '\n';
        } else {
            std::cerr << "Invalid input\n";
        }
    }

    return 0;
}

https://godbolt.org/z/4P5GY4afz

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。