简体   繁体   English

在C ++中的分度符之间提取子字符串

[英]Extract a substring between delimeters in C++

I have to get the substring "Debian GNU/Linux 8 (jessie)" that is between two quotes, like: 我必须得到两个引号之间的子字符串“ Debian GNU / Linux 8(jessie)”,例如:

PRETTY_NAME="Debian GNU/Linux 8 (jessie)"

But I don't know how to I can't manage to do that. 但是我不知道该怎么办。

The best code I actually have: 我实际上拥有的最佳代码:

std::ifstream osVersion("/usr/lib/os-release");
std::string os_str;
if (osVersion.is_open())
    getline(osVersion, os_str);
osVersion.close();
this->os = os_str.substr(os_str.find("\""), os_str.find("\""));

It gives an output like that: 它给出了这样的输出:

"Debian GNU/

The problem is when you do 问题是你什么时候做

this->os = os_str.substr(os_str.find("\""), os_str.find("\""));

find is finding the same " in each call. That means you are going to start your substring at the first " and then it will be N characters long where N is the position of the first " . find是找到相同的"在每次调用,这意味着你要开始你在第一子" ,然后它会N字符长,其中N是第一的位置"

You can fix this by capturing the posistion of the first " and using that to get the next one like 您可以通过捕获第一个"并使用它来获取下一个

std::size_t pos = os_str.find("\"");
this->os = os_str.substr(pos + 1, os_str.find("\"", pos + 1) - pos - 1);

Do note though that in order to make the code bullet proof you should be capturing both positions and making sure the do not equal std::string::npos If either of them do you have an improperly formatted sting and the above method will implode. 但是要注意,为了使代码更安全,您应该同时捕获两个位置并确保std::string::npos不相等。如果两个位置都不正确,则上述方法会崩溃。

std::find is easier to use here: std::find在这里更易于使用:

std::string::iterator begin = std::find(std::begin(os_str), std::end(os_str), '"');
if (begin != std::end(os_str)) {
    ++begin;
    std::string::iterator end = std::find(begin, std::end(os_str), '"');
    this->os = std::string(begin, end);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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