c++ - 我们可以在一条语句中拆分、操作和重新连接 C++ 中的字符串吗?

标签 c++ boost stl

这是一个有点愚蠢的问题,但出于好奇,是否有可能用 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/

上一篇:c++ - 项目的库位置

下一篇:C++ 视频处理

相关文章:

c++ - 如何动态调整 QLabel/QVBoxLayout/QWidget 中使用的 QImage 的大小

c++ - 可以使用 "and"、 "or"等代替 "&&"、 "||"吗?

c++ - 我需要帮助将 vcxproj 转换为 cmake

c++ - 如何使用boost从内存映射文件访问内存块?

c++ - Solaris 上的 Boost 库

c++ - 使用 boost::proto 在 C++ 中编写 DSL

c++ - 从字符串中解析数字

c++ - C++ 中的非刚体 2D 物理引擎

C++使用对象的优先级队列

c++ - 带有预分配缓冲区的循环缓冲区?