C++ 程序如何连接给定次数的字符串?

c++server side programmingprogramming

在这里我们将看到如何连接字符串 n 次。n 的值由用户给出。这个问题很简单。在 C++ 中,我们可以使用 + 运算符进行连接。请阅读代码以了解思路。

算法

concatStrNTimes(str, n)

begin
   res := empty string
   for i in range 1 to n, do
      res := concatenate res and res
   done
   return res
end

示例

#include<iostream>
using namespace std;
main() {
   string myStr, res = "";
   int n;
   cout << "输入字符串:";
   cin >> myStr;
   cout << "输入要连接的次数:";
   cin >> n;
   for(int i= 0; i < n; i++) {
      res += myStr;
   }
    cout << "结果: " << res;
}

输出

输入字符串:Hello
输入要连接的次数:5
结果:HelloHelloHelloHello

相关文章