โปรแกรมที่จะเชื่อมสตริงตามจำนวนครั้งที่กำหนดจะรันเมธอด string concatenate n จำนวนครั้งตามค่าของ n
ผลลัพธ์จะเป็นสตริงซ้ำหลายครั้ง
ตัวอย่าง
given string: “ I love Tutorials point” n = 5
ผลลัพธ์
I love Tutorials pointI love Tutorials pointI love Tutorials pointI love Tutorials point I love Tutorials point
หลังจากเห็นผลลัพธ์แล้วชัดเจนว่าฟังก์ชั่นนั้นจะทำอย่างไร
ตัวอย่าง
#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;
} ผลลัพธ์
I love tutorials pointI love tutorials pointI love tutorials pointI love tutorials point