Ở đây chúng ta sẽ thấy cách chúng ta có thể nối một chuỗi n với số lần. Giá trị của n do người dùng đưa ra. Vấn đề này rất đơn giản. Trong C ++ chúng ta có thể sử dụng toán tử + để nối. Vui lòng xem qua mã để lấy ý tưởng.
Thuật toán
concatStrNTimes (str, n)
begin res := empty string for i in range 1 to n, do res := concatenate res and res done return res end
Ví dụ
#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;
} Đầu ra
Enter String: Hello Enter number of times it will be concatenated: 5 Result: HelloHelloHelloHelloHello