如何在C ++中将字符串重复可变的次数?

时间:2020-03-06 15:04:21  来源:igfitidea点击:

我想在C ++中的字符串开头插入" n"个空格(或者任何字符串)。是否可以使用std :: strings或者char *字符串直接进行此操作?

例如。在Python中,我们可以简单地执行

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

解决方案

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

查看std :: string的构造函数。

我们应该编写自己的流操纵器

  • http://www.two-sdg.demon.co.uk/curbralan/papers/WritingStreamManipulators.html
cout << multi(5) << "whatever" <<
  "lolcat";

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

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

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

在C ++中,没有直接惯用的方式来重复字符串,等效于Python中的*运算符或者Perl中的x运算符。如果我们要重复单个字符,则由两个参数组成的构造函数(如先前的答案所建议)可以很好地工作:

std::string(5, '.')

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

#include <sstream>

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

取决于实现方式,这可能比简单地串联字符串n次更为有效。

我知道这是一个古老的问题,但是我一直想做同样的事情,并且发现了我认为更简单的解决方案。看来cout具有使用cout.fill()内置的此功能,请参阅链接以获取"完整"说明

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

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

输出

.....lolcat