简体   繁体   English

在字符串 C++ 中的字符之间添加空格

[英]Adding spaces between characters in string C++

I am looking for the most efficient way to add a space " " between every character in the string in C++.我正在寻找在 C++ 字符串中的每个字符之间添加空格" "的最有效方法。

So let's say I pass a string "123" and I want to get "1 2 3 " or "1 2 3" (it doesn't really matter).所以假设我传递了一个字符串"123" ,我想得到"1 2 3 ""1 2 3" (这并不重要)。

Does anyone know the fastest way of doing such a thing?有谁知道做这种事情的最快方法?

My method so far looks like this...到目前为止,我的方法看起来像这样......

    string output;
    for(int i = 0 ; i < s.length(); ++i) {
        output += s.substr(i, 1) + " ";
    }
    return output;

...but I'm just wondering if there's a better way to do it ...但我只是想知道是否有更好的方法来做到这一点

Thanks谢谢

You can write this conveniently with the range-v3 library.您可以使用 range-v3 库方便地编写它。 So given:所以给出:

namespace rs = ranges;
namespace rv = ranges::views;

std::string input = "123";

If you just want to print the string with interspersed spaces, you can do:如果只想打印带有空格的字符串,可以执行以下操作:

rs::copy(input | rv::intersperse(' '), 
         rs::ostream_iterator<char>(std::cout));

And if you want to store the result in a new string, you can do:如果要将结果存储在新字符串中,可以执行以下操作:

auto result = input | rv::intersperse(' ') | rs::to<std::string>;

Here's a demo .这是一个演示

I think this is about as efficient as it can reasonably get, but more importantly, it's very readable.我认为这与它可以合理获得的效率一样高,但更重要的是,它非常易读。

The inefficiency of your code is repeated re-allocation of the string.你的代码效率低下是重复重新分配字符串。

You know upfront the size of the output , so you should allocated that, filled with spaces.您预先知道output的大小,因此您应该分配它,并用空格填充。 Then you simply place all character in their new position:然后你只需将所有角色放在他们的新位置:

std::string foo(const std::string& s) {
  std::string output(s.length()*2-1, ' ');
  for (int i = 0, j = 0; i < s.length(); ++i, j+=2) {
    output[j] = s[i];
  }
  return output;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM