是否可以打印出与循环计数器相对应的字符串

Is it possible to print out a string corresponding to the counter of a loop

本文关键字:相对 计数器 字符串 循环 打印 是否      更新时间:2023-10-16

我尝试创建一个循环并使用append函数。示例:

string a = "hey";
for (int i = 0; i < 3; i++)
{
    cout << a << endl;
    a += a;
}

例如,如果我想打印

heyheyhey
heyhey
hey

那么这个方法就会失败。

但是如果我想打印

hey
heyday
heyheyhey

那么这种方法就会起作用;因为append函数根据循环迭代次数将字符串添加到末尾。有可能按照我尝试的方式解决这个问题吗?或者有没有一种方法可以递归地交换底层解决方案以获得顶层解决方案?我一直在学习字符串,我希望我可以使用字符串函数来解决这个问题。

有两种方法:

  1. 从大字符串开始,擦除碎片
  2. 使用嵌套循环

对于大字符串,您需要从"嘿嘿"开始打印字符串,然后在每个循环中删除一个"嘿"。这与串联相反。

另一种方法是使用嵌套循环:

for (unsigned int line = 0; line < 3; ++line)
{
  for (unsigned int copies_per_line = 0; copies_per_line < (3 - line); ++copies_per_line)
  {
    cout << "hey";
  }
  cout << "n";
}

只需将cout固定在for循环中即可。只是要注意如何处理条件和增量。

您可以创建一个将文本打印X次的可选函数:

void printCount(string text, int count)
{
    for(int now = 0; now < count; now++)
        printf(text);
}

然后你可以创建主循环,显示你的文本:

for(int now = 0; now < 3; now++)
    printCount("hey", now + 1);

现在+1意味着在周期0中,我们需要打印1条消息,在周期1-2和更多

针对您的情况:

for(int now = 3; now > 0; now--)
    printCount("hey", now);

编辑:你也可以使用cout:

void printCount(string text, int count)
{
    for(int now = 0; now < count; now++)
        cout << text;
    cout << endln;
}
顺便说一句,即使在第二种情况下,您的方法也会失败。它不会打印
hey
heyday
heyheyhey

但是

hey
heyhey
heyheyheyhey

因为字符串在每次迭代中总是加倍。

正如其他答案所述,您可以简单地使用一个额外的内部循环。

string a = "hey";
for(int i = 3; i > 0; i--)
{
    for(int j = i; j > 0; j--)
        cout << a;
    cout << endl;
}

不幸的是,这并不像看上去那么微不足道。我看到了两个潜在的解决方案:第一次将输出存储在循环中并在第二个循环中打印,或者第一次创建a并在第三个循环中创建输出。不管怎样,我都看不出如何在一个循环中做到这一点。

由于将字符串复制到数组中有点烦人,下面是第二个解决方案。

string a = "hey";
for (int i = 0; i < 3; i++)
  a += a;
for (int j = 0; j < 3; j++) {
  int copyLength = (3 - j) * "hey".length();
  cout << a.substr(0, copyLength) << endl;
}

注意:我强烈考虑将3设为const,或者至少设为此处的变量。上述代码中3的所有实例都应该一起更改。

目前尚不清楚您对自己施加了什么样的任意限制,但可以通过多种方式轻松获得输出。这里有一个递归解决方案:

std::string repeat(std::string str, int rpt)
{
    return (rpt > 1) ? str + repeat(str, rpt - 1) : str; 
}
int main()
{
    for (int i = 3; i > 0; i--)
    {
        std::string a = repeat( "hey", i);
        std::cout << a << std::endl;
    }
    return 0;
}