有没有办法在 C 中实现 Python 的“分隔符”.join() 的模拟?
我发现的只是 boost::algorithm::string::join
。然而,仅使用 Boost 进行连接似乎有点矫枉过正。那么也许有一些经过时间考验的食谱?
更新:
抱歉,问题标题不好。 我正在寻找用分隔符连接字符串的方法,而不仅仅是一一连接。
All I've found is boost::algorithm::string::join
. However, it seems like overkill to use Boost only for join. So maybe there are some time-tested recipes?
UPDATE:
Sorry, the question caption were bad.
I'm looking for method to concatenate strings with separator, not just to concatenate one-by-one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
既然您正在寻找一个配方,请继续使用 Boost 中的配方。一旦你克服了所有的通用性,它就不会太复杂:
这是一个在两个迭代器上运行的版本(与在范围上运行的 Boost 版本相反。
Since you're looking for a recipe, go ahead and use the one from Boost. Once you get past all the genericity, it's not too complicated:
Here's a version that works on two iterators (as opposed to the Boost version, which operates on a range.
如果您确实想要
''.join()
,您可以将std::copy
与std::ostream_iterator
一起使用到std::stringstream
。这会将所有值插入到缓冲区中。您还可以为
std::ostream_iterator
指定自定义分隔符,但这将附加在末尾(这是与join
的显着区别)。如果您不需要分隔符,这将满足您的需求。If you really want
''.join()
, you can usestd::copy
with anstd::ostream_iterator
to astd::stringstream
.This will insert all the values to
buffer
. You can also specify a custom separator forstd::ostream_iterator
but this will get appended at the end (this is the significant difference tojoin
). If you don't want a separator, this will do just what you want.简单来说,容器中的类型是 int:
simply, where the type in the container is an int:
这适用于 C++17:
它应该打印:
This works with C++17:
It should print:
C++ 字符串的实现非常高效。
这可能会更快:
但这基本上就是编译器使用
operator+
所做的事情,并且进行了最低限度的优化,除了猜测要保留的大小之外。别害羞。看一下 字符串的实现。 :)
C++ strings are implemented efficiently.
This could be faster:
But this is basically what your compiler do with
operator+
and a minimum of optimization except it is guessing the size to reserve.Don't be shy. Take a look at the implementation of strings. :)
这是我发现更方便使用的另一个版本:
然后您可以这样调用它:
Here is another version that I find more handy to use:
You can then call it this way:
如果您在项目中使用Qt,则可以直接使用QString的
join
函数(QString 参考)并且它按照 python 的预期工作。一些示例:结果:
""
结果:
"id = 1"
结果:
"id = 1 and name = me"
If you use Qt in your project you can directly use the
join
function of QString (QString Reference) and it works as expected from python. Some examples:Result:
""
Result:
"id = 1"
Result:
"id = 1 and name = me"
这是另一个简单的解决方案:
对于那些不喜欢
begin()
、end()
作为参数并且更喜欢整个容器的人。对于那些不喜欢字符串流而更喜欢一些operator std::string() const
的人来说。用法:
应该与 C++11 及更高版本一起使用。
Just another simple solution:
For those who don't like
begin()
,end()
as arguments and prefer just the whole container. And for those who don't like string streams and prefer someoperator std::string() const
instead.Usage:
Should work with C++11 and later.