C ++에서 문자열을 가변 횟수로 반복하는 방법은 무엇입니까?
C ++에서 문자열 시작 부분에 'n'공백 (또는 임의의 문자열)을 삽입하고 싶습니다. std :: strings 또는 char * 문자열을 사용하여이를 수행하는 직접적인 방법이 있습니까?
예를 들어 Python에서는 간단히 할 수 있습니다.
>>> "." * 5 + "lolcat"
'.....lolcat'
단일 문자를 반복하는 특별한 경우 다음을 사용할 수 있습니다 std::string(size_type count, CharT ch)
.
std::string(5, '.') + "lolcat"
NB. 여러 문자 문자열을 반복하는 데 사용할 수 없습니다.
Python 의 * 연산자 또는 Perl 의 x 연산자에 해당하는 C ++에서 문자열을 반복하는 직접적인 관용적 방법은 없습니다 . 단일 문자를 반복하는 경우 이전 답변에서 제안한대로 두 인수 생성자가 잘 작동합니다.
std::string(5, '.')
이것은 ostringstream을 사용하여 문자열을 n 번 반복하는 방법에 대한 인위적인 예입니다.
#include <sstream>
std::string repeat(int n) {
std::ostringstream os;
for(int i = 0; i < n; i++)
os << "repeat";
return os.str();
}
구현에 따라 이것은 단순히 문자열을 n 번 연결하는 것보다 약간 더 효율적일 수 있습니다.
string :: insert 형식 중 하나를 사용합니다.
std::string str("lolcat");
str.insert(0, 5, '.');
이렇게하면 문자열 시작 (위치 0)에 "....."(점 5 개)가 삽입됩니다.
나는 이것이 오래된 질문이라는 것을 알고 있지만 똑같은 일을 찾고 있었고 더 간단한 해결책이라고 생각하는 것을 발견했습니다. cout에는이 함수가 cout.fill ()과 함께 내장되어있는 것으로 보입니다. '전체'설명은 링크를 참조하십시오.
http://www.java-samples.com/showtutorial.php?tutorialid=458
cout.width(11);
cout.fill('.');
cout << "lolcat" << endl;
출력
.....lolcat
Commodore Jaeger가 언급했듯이, 나는 다른 답변 중 어떤 것도 실제로이 질문에 대답하지 않는다고 생각합니다. 질문은 문자가 아닌 문자열을 반복하는 방법을 묻습니다.
Commodore가 제공 한 대답은 정확하지만 매우 비효율적입니다. 다음은 더 빠른 구현입니다. 아이디어는 먼저 문자열을 기하 급수적으로 늘려 복사 작업 및 메모리 할당을 최소화하는 것입니다.
#include <string>
#include <cstddef>
std::string repeat(std::string str, const std::size_t n)
{
if (n == 0) {
str.clear();
str.shrink_to_fit();
return str;
} else if (n == 1 || str.empty()) {
return str;
}
const auto period = str.size();
if (period == 1) {
str.append(n - 1, str.front());
return str;
}
str.reserve(period * n);
std::size_t m {2};
for (; m < n; m *= 2) str += str;
str.append(str.c_str(), (n - (m / 2)) * period);
return str;
}
operator*
파이썬 버전에 더 가까운 것을 얻기 위해를 정의 할 수도 있습니다 .
#include <utility>
std::string operator*(std::string str, std::size_t n)
{
return repeat(std::move(str), n);
}
내 컴퓨터에서 이것은 Commodore가 제공 한 구현보다 약 10 배 빠르며 순진한 'append n-1 times' 솔루션 보다 약 2 배 빠릅니다 .
자신 만의 스트림 조작기를 작성해야합니다.
cout << multi (5) << "whatever"<< "lolcat";
ITNOA
이를 위해 C ++ 함수를 사용할 수 있습니다.
std::string repeat(const std::string& input, size_t num)
{
std::ostringstream os;
std::fill_n(std::ostream_iterator<std::string>(os), num, input);
return os.str();
}
For the purposes of the example provided by the OP std::string's ctor is sufficient: std::string(5, '.')
. However, if anybody is looking for a function to repeat std::string multiple times:
std::string repeat(const std::string& input, unsigned num)
{
std::string ret;
ret.reserve(input.size() * num);
while (num--)
ret += input;
return ret;
}
참고URL : https://stackoverflow.com/questions/166630/how-to-repeat-a-string-a-variable-number-of-times-in-c
'Programing' 카테고리의 다른 글
부트 스트랩 모달 : 토글시 배경이 맨 위로 이동 (0) | 2020.08.17 |
---|---|
leftAnchor와 leadingAnchor의 차이점은 무엇입니까? (0) | 2020.08.17 |
iOS-프로그래밍 방식으로 UISwitch를 설정하는 방법 (0) | 2020.08.17 |
WebException 본문으로 전체 응답을 얻는 방법은 무엇입니까? (0) | 2020.08.17 |
UITableView 동적 셀 높이는 일부 스크롤 후에 만 수정됩니다. (0) | 2020.08.17 |