简体   繁体   中英

How to get a particular part of string in c++?

I have the below string i need take out the id (68890) similar date (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)

How can i achieve this in C++ is there any way to do in regex or any functions available.

The simplest way using standard library is to use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM