gpt4 book ai didi

C++ STL 在逗号处拆分字符串

转载 作者:太空狗 更新时间:2023-10-29 22:56:10 25 4
gpt4 key购买 nike

我知道几个相关问题,例如 Parsing a comma-delimited std::string一。但是,我已经创建了一个适合我特定需要的代码——在逗号处拆分字符串(从文件中读取),去除任何空格。稍后我想将这些子字符串转换为 double并存储在std::vector .并未显示所有操作。这是我提供的代码。

include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>

int main()
{
std::string str1 = " 0.2345, 7.9 \n", str2;
str1.erase(remove_if(str1.begin(), str1.end(), isspace), str1.end()); //remove whitespaces
std::string::size_type pos_begin = { 0 }, pos_end = { 0 };


while (str1.find_first_of(",", pos_end) != std::string::npos)
{
pos_end = str1.find_first_of(",", pos_begin);
str2 = str1.substr(pos_begin, pos_end- pos_begin);
std::cout << str2 << std::endl;
pos_begin = pos_end+1;
}

}

输出:

0.2345
7.9

所以程序是这样的。 While 循环搜索 , 的出现pos_end将存储第一次出现的 , , str2将是一个子串,pos_begin将转到 pos_end 旁边的一个.第一次迭代将运行良好。

在下一次迭代中,pos_end将是非常大的值(value),我不确定是什么pos_end- pos_begin将。同样适用于 pos_begin (尽管它不会被使用)。正在做一些检查,比如

if (pos_end == std::string::npos)
pos_end = str1.length();

一条路要走?

尽管该程序仍在运行(g++ -Wall -Wextra prog.cpp -o prog -std=c++11)。这种做法是否正确?

最佳答案

您的删除习惯用法可能无法在更现代的编译器上编译,因为 isspace 已过载。在某些时候,使用 range-for 删除空格可能更有效。有问题的算法取决于您是否需要存储 token 纠正行中的“语法”错误并存储或不存储空 token 。

#include<iostream>
#include<string>
#include<list>
#include<algorithm>

typedef std::list<std::string> StrList;



void tokenize(const std::string& in, const std::string& delims, StrList& tokens)
{
tokens.clear();

std::string::size_type pos_begin , pos_end = 0;
std::string input = in;

input.erase(std::remove_if(input.begin(),
input.end(),
[](auto x){return std::isspace(x);}),input.end());

while ((pos_begin = input.find_first_not_of(delims,pos_end)) != std::string::npos)
{
pos_end = input.find_first_of(delims,pos_begin);
if (pos_end == std::string::npos) pos_end = input.length();

tokens.push_back( input.substr(pos_begin,pos_end-pos_begin) );
}
}

int main()
{
std::string str = ",\t, 0.2345,, , , 7.9 \n";
StrList vtrToken;

tokenize( str, "," , vtrToken);

int i = 1;
for (auto &s : vtrToken)
std::cout << i++ << ".) " << s << std::endl;

return 0;
}

输出:

1.) 0.2345
2.) 7.9

此变体会去除所有空标记。在您的上下文中是否正确是未知的,因此没有正确答案。如果你必须检查字符串是否正确,或者如果你用默认值替换了空标记,你必须添加额外的检查

关于C++ STL 在逗号处拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48818159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com