ที่นี่เราจะดูว่าเราสามารถเชื่อมสตริง 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