Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Nối chuỗi lặp lại N lần trong C++

Chương trình nối chuỗi một số lần cho trước sẽ chạy phương thức nối chuỗi n lần dựa trên giá trị n. Kết quả là chuỗi được lặp lại n lần.

Ví dụ

Chuỗi: "I love Tutorials point"
n = 5

Kết quả

I love Tutorials pointI love Tutorials pointI love Tutorials pointI love Tutorials pointI love Tutorials point

Code ví dụ

#include <iostream>
#include <string>
using namespace std;

string repeat(string s, int n) {
    string result = s;
    for (int i = 1; i < n; i++)
        result += s;  // Nối chuỗi
    return result;
}

int main() {
    string s = "I love tutorials point";
    int n = 4;
    
    string result = repeat(s, n);
    cout << result << endl;
    return 0;
}

Kết quả

I love tutorials pointI love tutorials pointI love tutorials pointI love tutorials point

Cách tối ưu hơn (C++11 trở lên)

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s = "I love tutorials point";
    int n = 4;
    string result;
    result.reserve(s.length() * n); // Dự trữ bộ nhớ
    
    for (int i = 0; i < n; i++)
        result += s;
    
    cout << result << endl;
    return 0;
}

Sử dụng reserve() giúp tránh reallocation nhiều lần, tăng hiệu năng khi n lớn.