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

在这里,我们将看到如何将字符串连接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 << "Enter String: ";
   cin >> myStr;
   cout << "Enter number of times it will be concatenated: ";
   cin >> n;
   for(int i= 0; i < n; i++) {
      res += myStr;
   }
   cout << "Result: " << res;
}

输出结果

Enter String: Hello
Enter number of times it will be concatenated: 5
Result: HelloHelloHelloHelloHello