Một chương trình để nối một chuỗi với một số lần nhất định sẽ chạy phương thức nối chuỗi n số lần dựa trên giá trị của n.
Kết quả sẽ là chuỗi được lặp lại một số lần.
Ví dụ
given string: “ I love Tutorials point” n = 5
Đầu ra
I love Tutorials pointI love Tutorials pointI love Tutorials pointI love Tutorials point I love Tutorials point
Sau khi xem kết quả, rõ ràng là chức năng sẽ thực hiện những gì.
Ví dụ
#include <iostream>
#include <string>
using namespace std;
string repeat(string s, int n) {
string s1 = s;
for (int i=1; i<n;i++)
s += s1; // Concatinating strings
return s;
}
// Driver code
int main() {
string s = "I love tutorials point";
int n = 4;
string s1 = s;
for (int i=1; i<n;i++)
s += s1;
cout << s << endl;;
return 0;
} Đầu ra
I love tutorials pointI love tutorials pointI love tutorials pointI love tutorials point