c++字符串分隔符异常



我正在编写一段代码,遇到了一个小问题。总的来说,问题在于字符串分隔符和c++ std::string的分割。

我的字符串是:

std::string nStr = 
R"(
"0000:ae:05.2:
Address: 0000:ae:05.2
Segment: 0x0000
")";

通常上面的内容更大,并且包含更多的数据项。我设置的分隔符是": "因为它将是数据中最常用的分隔符。我的目标是得到2个字符串,即string1 = Address和string2 = 0000:ae:05.2,但我也需要第一行进行类似的处理,所以基本上它都应该从string1 = header和string2 = 0000:ae:05.2开始

我的代码现在看起来是这样的:

int main(int argc, char* argv[])
{
std::string nStr = 
R"(
"0000:ae:05.2:
Address: 0000:ae:05.2
Segment: 0x0000
")";
std::string tLine1="", tLine2="";
//nStr = nStr.erase(nStr.find_last_not_of("nrt"));   
const std::string delimiter = ": ", delim2=":";
std::string::size_type pos = nStr.find(delimiter);
std::string::size_type pos2 = nStr.find(delim2);
if(nStr.npos != pos){
tLine2 = nStr.substr(pos + 1);
tLine1 = nStr.substr(0, pos);
}
else if(nStr.npos != pos2){
tLine1 = nStr.substr(0, pos2);
tLine2 = "blank";
}
else
std::cout << "Delimiter not specified!n";

main"分隔符,": "而不是为了" "它也不会读取所有的"; "分隔符。

我的输出是:tLine1 ="0000:ae: 05.2:地址tLine2 = 0000: ae: 05.2段:0 x0000

关于如何正确地做到这一点,有什么想法吗?或者如何以更好的方式解决这个问题?提前谢谢。

下面的代码可以满足您的要求。

#include<iostream>
#include<string>
int main(int argc, char* argv[])
{
std::string nStr =
R"(0000:ae:05.2:Address: 0000:ae:05.2 Segment: 0x0000
)";
std::string tLine1 = "", tLine2 = "";
const std::string delimiter = ": ";
size_t pos = 0;

while ((pos = nStr.find(delimiter)) != std::string::npos) {
tLine1 = nStr.substr(0, pos);
nStr.erase(0, pos + delimiter.length());
tLine2 = nStr;
break;
}
std::cout << "tLine1 = " << tLine1<<"n";
std::cout << "tLine2 = " << tLine2<<"n";
}

输出:

tLine1 = 0000:ae:05.2:Address
tLine2 = 0000:ae:05.2 Segment: 0x0000

好的,从你的评论中我可以理解,你想把原始字符串分成几行,然后用":"作为分隔符。除了第一行,它只有一个值。因此,本行的结果对应该包含本行的值和字符串字面值"header"

#include <iostream>
#include <string>
#include <utility>
auto splitLine(const std::string& line) {
using namespace std::string_literals;
auto delimiterPos = line.find(": ");
if (delimiterPos != std::string::npos) {
return std::make_pair(line.substr(0, delimiterPos),
line.substr(delimiterPos + 2));
}
return std::make_pair(line.substr(1, line.size() - 2), "header"s);
}
int main(int argc, char* argv[]) {
std::string nStr =
R"(
"0000:ae:05.2:
Address: 0000:ae:05.2
Segment: 0x0000
")";
std::size_t newLinePos;
do {
newLinePos = nStr.find("n");
std::string line = nStr.substr(0, newLinePos);
nStr = nStr.substr(newLinePos + 1);
// To ignore empty lines and the last line that just contains a double quote
if (line.size() == 0 || line == """) {
continue;
}
auto lines = splitLine(line);
std::cout << "line1: " << lines.first << "n";
std::cout << "line2: " << lines.second << "n";
} while (newLinePos != std::string::npos);
}

我不能100%确定每行的哪一部分被认为是第一个值,哪一部分是第二个值。看起来你在问题和评论之间来回切换。但是你应该能够根据你的愿望来改变它。

我没有完全掌握的另一个方面是原始字符串的布局。它似乎以一个新的行字符开始。并以新行结束,后跟双引号。我必须特别抓住那些。

和第一个"头"行以双引号开始,以冒号结束。我只是希望总是如此,并从所述行中删除了第一个和最后一个字符。

这将帮助如果我们有一个更好的例子输入数据。

最新更新