是否可以打印出与循环计数器相对应的字符串
Is it possible to print out a string corresponding to the counter of a loop
我尝试创建一个循环并使用append函数。示例:
string a = "hey";
for (int i = 0; i < 3; i++)
{
cout << a << endl;
a += a;
}
例如,如果我想打印
heyheyhey
heyhey
hey
那么这个方法就会失败。
但是如果我想打印
hey
heyday
heyheyhey
那么这种方法就会起作用;因为append函数根据循环迭代次数将字符串添加到末尾。有可能按照我尝试的方式解决这个问题吗?或者有没有一种方法可以递归地交换底层解决方案以获得顶层解决方案?我一直在学习字符串,我希望我可以使用字符串函数来解决这个问题。
有两种方法:
- 从大字符串开始,擦除碎片
- 使用嵌套循环
对于大字符串,您需要从"嘿嘿"开始打印字符串,然后在每个循环中删除一个"嘿"。这与串联相反。
另一种方法是使用嵌套循环:
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;
}
相关文章:
- 循环在计数器中不起作用
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- python集合的C++等价物是什么.计数器
- 如何使用cppcheck处理半相对包含路径
- Python 集合.计数器,如何避免重复查找
- 请解释字谜的代码,我看不懂计数器数组,每个值已经是0
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- std::shared_ptr 自定义参考计数器
- 使用哈希图进行相对排序
- 英特尔 TBB 程序不会终止,可能会误用参考计数器
- 有没有办法保证析构函数的相对顺序?
- 不正确的比较和交换计数器输出用于快速排序功能
- Windows 和 Linux 之间的相对路径分辨率差异?
- OpenSSL API,使用GCM(伽罗瓦计数器模式)进行AES加密
- C++ 在循环中添加计数器变量并再次初始化其值
- 为什么从具有较大阵列的 SIMD 内部函数中获得的相对加速比标量更大?
- MOVNTI 存储是否相对于由同一线程创建的其他 MOVNTI 存储重新排序?
- 如何获取 CMake 单元测试的相对路径?
- 是否可以打印出与循环计数器相对应的字符串
- 我该如何添加与表的每个哈希地址相对应的计数器