cpp에서 문자열 multiplication을 수행하는 방법은 여러가지가 있지만, 가장 간단한 방법을 소개해보고자 한다.
std::string에는 다음과 같은 constructor가 존재한다.
std::string(size_type count, char c);
이를 이용하여 문자열 multiplication을 수행하면 다음과 같다.
"ab"를 5번 반복한 문자열을 출력하는 코드이다.
#include<iostream>
using namespace std;
#include<string>
int main()
{
string x = "ab";
string y = "";
int cnt = 5;
for(int i=0; i<x.length(); i++)
{
string add(cnt, x[i]);
y += add;
}
cout << y << endl;
return 0;
}
다음 코드의 결과는 "ab"가 5번 반복되는 "ababababab"가 나오게 된다.