如何在 C++ 中多次重复字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/166630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:24:56  来源:igfitidea点击:

How to repeat a string a variable number of times in C++?

c++

提问by luke

I want to insert 'n' spaces (or any string) at the beginning of a string in C++. Is there any direct way to do this using either std::strings or char* strings?

我想在 C++ 中的字符串开头插入 'n' 个空格(或任何字符串)。有没有使用 std::strings 或 char* 字符串的直接方法?

E.g. in Python you could simply do

例如在 Python 中你可以简单地做

>>> "." * 5 + "lolcat"
'.....lolcat'

回答by luke

In the particular case of repeating a single character, you can use std::string(size_type count, CharT ch):

在重复单个字符的特殊情况下,您可以使用std::string(size_type count, CharT ch)

std::string(5, '.') + "lolcat"

NB. This can't be used to repeat multi-character strings.

注意。这不能用于重复多字符串。

回答by Commodore Jaeger

There's no direct idiomatic way to repeat strings in C++ equivalent to the *operator in Python or the xoperator in Perl. If you're repeating a single character, the two-argument constructor (as suggested by previous answers) works well:

在 C++ 中没有直接的惯用方式来重复字符串,相当于Python 中的*运算符或Perl 中的x运算符。如果您重复单个字符,则双参数构造函数(如先前答案所建议的那样)效果很好:

std::string(5, '.')

This is a contrived example of how you might use an ostringstream to repeat a string n times:

这是一个人为的示例,说明如何使用 ostringstream 将字符串重复 n 次:

#include <sstream>

std::string repeat(int n) {
    std::ostringstream os;
    for(int i = 0; i < n; i++)
        os << "repeat";
    return os.str();
}

Depending on the implementation, this may be slightly more efficient than simply concatenating the string n times.

根据实现,这可能比简单地将字符串连接 n 次更有效。

回答by camh

Use one of the forms of string::insert:

使用 string::insert 的一种形式:

std::string str("lolcat");
str.insert(0, 5, '.');

This will insert "....." (five dots) at the start of the string (position 0).

这将在字符串的开头(位置 0)插入“.....”(五个点)。

回答by Ian

I know this is an old question, but I was looking to do the same thing and have found what I think is a simpler solution. It appears that cout has this function built in with cout.fill(), see the link for a 'full' explanation

我知道这是一个老问题,但我想做同样的事情,并找到了我认为更简单的解决方案。似乎 cout 在 cout.fill() 中内置了此功能,请参阅“完整”解释的链接

http://www.java-samples.com/showtutorial.php?tutorialid=458

http://www.java-samples.com/showtutorial.php?tutorialid=458

cout.width(11);
cout.fill('.');
cout << "lolcat" << endl;

outputs

产出

.....lolcat

回答by Daniel

As Commodore Jaeger alluded to, I don't think any of the other answers actually answer this question; the question asks how to repeat a string, not a character.

正如 Commodore Jaeger 所暗示的那样,我认为其他任何答案都不能真正回答这个问题;该问题询问如何重复一个字符串,而不是一个字符。

While the answer given by Commodore is correct, it is quite inefficient. Here is a faster implementation, the idea is to minimise copying operations and memory allocations by first exponentially growing the string:

Commodore 给出的答案是正确的,但效率很低。这是一个更快的实现,其想法是通过首先以指数方式增长字符串来最小化复制操作和内存分配:

#include <string>
#include <cstddef>

std::string repeat(std::string str, const std::size_t n)
{
    if (n == 0) {
        str.clear();
        str.shrink_to_fit();
        return str;
    } else if (n == 1 || str.empty()) {
        return str;
    }
    const auto period = str.size();
    if (period == 1) {
        str.append(n - 1, str.front());
        return str;
    }
    str.reserve(period * n);
    std::size_t m {2};
    for (; m < n; m *= 2) str += str;
    str.append(str.c_str(), (n - (m / 2)) * period);
    return str;
}

We can also define an operator*to get something closer to the Python version:

我们还可以定义一个operator*更接近 Python 版本的东西:

#include <utility>

std::string operator*(std::string str, std::size_t n)
{
    return repeat(std::move(str), n);
}

On my machine this is around 10x faster than the implementation given by Commodore, and about 2x faster than a naive 'append n - 1 times'solution.

在我的机器上,这比 Commodore 给出的实现快 10 倍左右,比简单的“追加 n - 1 次”解决方案快2 倍左右

回答by Roskoto

You should write your own stream manipulator

您应该编写自己的流操纵器

cout << multi(5) << "whatever" << "lolcat";

cout << multi(5) << "whatever" << "lolcat";

回答by Pavel P

For the purposes of the example provided by the OP std::string's ctor is sufficient: std::string(5, '.'). However, if anybody is looking for a function to repeat std::string multiple times:

对于 OP std::string 的构造函数提供的示例而言,就足够了:std::string(5, '.'). 但是,如果有人正在寻找一个函数来多次重复 std::string:

std::string repeat(const std::string& input, unsigned num)
{
    std::string ret;
    ret.reserve(input.size() * num);
    while (num--)
        ret += input;
    return ret;
}

回答by sorosh_sabz

ITNOA

ITNOA

You can use C++ function for doing this.

您可以使用 C++ 函数来执行此操作。

 std::string repeat(const std::string& input, size_t num)
 {
    std::ostringstream os;
    std::fill_n(std::ostream_iterator<std::string>(os), num, input);
    return os.str();
 }