将特定字符组合下面的字符串拆分为字符串向量的正确方法是什么?
string myString = "This is \n a test. Let's go on. \n Yeah.";
在"\n"
处拆分以获得此结果:
vector<string> myVector = {
"This is ",
" a test. Let's go on. ",
" Yeah."
}
我正在使用 boost algorithm 库,但现在我想在不使用像boost这样的外部库的情况下实现这一切。
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
std::vector<std::string> result;
boost::split(result, "This is \n a test. Let's go on. \n Yeah.",
boost::is_any_of("\n"), boost::token_compress_on);
答案 0 :(得分:1)
这样的事情怎么样:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <iterator>
class line : public std::string {};
std::istream &operator>>(std::istream &iss, line &line)
{
std::getline(iss, line, '\n');
return iss;
}
int main()
{
std::istringstream iss("This is \n a test. Let's go on. \n Yeah.");
std::vector<std::string> v(std::istream_iterator<line>{iss}, std::istream_iterator<line>{});
// test
for (auto const &s : v)
std::cout << s << std::endl;
return 0;
}
基本上创建一个新类型的字符串,它是行并使用流迭代器直接读取整行到矢量范围构造函数
答案 1 :(得分:0)
解决方案1:只需从字符串中删除
"\n"
。
要删除"\n"
,您可以使用erase-remove idiom。 SEE LIVE HERE
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string myString = "This is \n a test. Let's go on. \n Yeah.";
myString.erase(std::remove(myString.begin(), myString.end(), '\n'),
myString.end());
std::cout << myString<< std::endl;
}
输出:
This is a test. Let's go on. Yeah
解决方案2 :从字符串中删除
"\n"
并将\n
处的每个拆分保存到矢量。 (未有效)
将所有\n
替换为其他一些字符串,这些字符串不存在于字符串中(此处我已选择;
)。然后在std::stringstream
和std::getline
的帮助下进行解析,如下所示。 SEE LIVE HERE
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
int main()
{
std::string myString = "This is \n a test. Let's go on. \n Yeah.";
std::replace(myString.begin(), myString.end(), '\n', ';');
std::stringstream ssMyString(myString);
std::string each_split;
std::vector<std::string> vec;
while(std::getline(ssMyString, each_split, ';')) vec.emplace_back(each_split);
for(const auto& it: vec) std::cout << it << "\n";
}
输出:
This is
a test. Let's go on.
Yeah.
解决方案3 :从字符串中删除
"\n"
并将\n
处的每个拆分保存到矢量。
遍历字符串并找到std::string::find
(结束位置)找到的位置(使用\n
)。使用起始位置信息和起始位置与结束位置之间的字符数来推回子串(std::string::substr
)。每次更新开始和结束位置,以便查找不会再从输入字符串的边缘开始。 SEE LIVE HERE
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstddef>
int main()
{
std::string myString = "This is \n a test. Let's go on. \n Yeah.";
std::vector<std::string> vec;
std::size_t start_pos = 0;
std::size_t end_pos = 0;
while ((end_pos = myString.find("\n", end_pos)) != std::string::npos)
{
vec.emplace_back(myString.substr(start_pos, end_pos - start_pos));
start_pos = end_pos + 1;
end_pos += 2;
}
vec.emplace_back(myString.substr(start_pos, myString.size() - start_pos)); // last substring
for(const auto& it: vec) std::cout << it << "\n";
}
输出:
This is
a test. Let's go on.
Yeah.