Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การต่อสตริงซ้ำจำนวนครั้งที่กำหนดใน C++


โปรแกรมต่อสตริงจำนวนครั้งที่กำหนดจะรันเมธอดการต่อสตริง 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; // Concatenating 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