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

โปรแกรม C++ ต่อสตริงซ้ำจำนวนครั้งที่กำหนด


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

int 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