这是一个有点愚蠢的问题,但出于好奇,是否有可能用 C++ 在一个语句中用逗号分割字符串,对字符串执行一个函数,然后用逗号重新连接它?
这是我到目前为止所拥有的:
string dostuff(const string& a) {
return string("Foo");
}
int main() {
string s("a,b,c,d,e,f");
vector<string> foobar(100);
transform(boost::make_token_iterator<string>(s.begin(), s.end(), boost::char_separator<char>(",")),
boost::make_token_iterator<string>(s.end(), s.end(), boost::char_separator<char>(",")),
foobar.begin(),
boost::bind(&dostuff, _1));
string result = boost::algorithm::join(foobar, ",");
}
因此这将导致将 "a,b,c,d,e,f"
转换为 "Foo,Foo,Foo,Foo,Foo,Foo"
我意识到这是 OTT,但只是想扩展我的 boost 魔法。
最佳答案
首先,请注意您的程序会写入“Foo,Foo,Foo,Foo,Foo,Foo,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,”到你的结果字符串 - 正如评论中已经提到的,你想在那里使用 back_inserter 。
至于答案,每当某个范围产生单个值时,我都会查看 std::accumulate
(因为是 fold/减少的 C++ 版本)
#include <string>
#include <iostream>
#include <numeric>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
std::string dostuff(const std::string& a) {
return std::string("Foo");
}
int main() {
std::string s("a,b,c,d,e,f");
std::string result =
accumulate(
++boost::make_token_iterator<std::string>(s.begin(), s.end(), boost::char_separator<char>(",")),
boost::make_token_iterator<std::string>(s.end(), s.end(), boost::char_separator<char>(",")),
dostuff(*boost::make_token_iterator<std::string>(s.begin(), s.end(), boost::char_separator<char>(","))),
boost::bind(std::plus<std::string>(), _1,
bind(std::plus<std::string>(), ",",
bind(dostuff, _2)))); // or lambda, for slightly better readability
std::cout << result << '\n';
}
只不过现在它已经超出了顶部并重复 make_token_iterator 两次。我猜 boost.range 获胜。
关于c++ - 我们可以在一条语句中拆分、操作和重新连接 C++ 中的字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3753725/