【问题标题】:How to get a particular part of string in c++?如何在 C++ 中获取字符串的特定部分?
【发布时间】:2021-08-12 18:57:33
【问题描述】:

我有以下字符串,我需要取出 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++ 中实现这一点,有什么方法可以在正则表达式或任何可用的函数中做。

【问题讨论】:

  • 要删除的标记是否总是用括号括起来?
  • 没有括号必须被删除。只需要 id : 68890 like this 或 68890 .

标签: c++ visual-studio c++11


【解决方案1】:

使用标准库最简单的方法是使用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

【讨论】:

  • 我提供了完整的工作示例,我无法帮助您解决我看不到的问题。我猜你忘了添加#include &lt;ctime&gt;
  • Marek 谢谢我解决了这个问题。但是当我添加一个字符串并放入 %s 来捕获它时。它失败了,我会更新我的问题,请检查
  • CString strsample = 这是演示 (Sample,Application),用于捕获日期 (01/14/2005) 父 ID (68890) 的详细信息,读取 (0) Total(%5)
  • 能否请您再检查一遍问题
  • 此编辑未提供您需要更多帮助的信息。我不知道你现在有什么问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
  • 1970-01-01
相关资源
最近更新 更多