std::string::substr (c++)

KimY·2025년 3월 2일

std::string::substr

  • std::string::substr은 string의 원하는 곳에서 원하는 길이만큼의 문자열을 가져올 때 사용한다.

  • 사용 방법

(문자열).substr(시작점, 길이)
// '시작점'에서 '길이'만큼의 문자열 리턴
or

(문자열).substr(시작점)
// '시작점'에서 끝까지 문자열 리턴

사용 예시

#include <iostream>

using namespace std;

int main() {
	string alphabet = "abcdefgh";

	/* 시작점와 길이 모두 사용 */
	cout << alphabet.substr(0, 1) << endl; // a
	cout << alphabet.substr(1, 1) << endl; // b
	cout << alphabet.substr(2, 1) << endl; // c

	cout << alphabet.substr(0, 2) << endl; // ab

	cout << alphabet.substr(1, 3) << endl; // bcd

	/* 시작점만 사용 */
	cout << alphabet.substr(1) << endl; // bcdefgh
	cout << alphabet.substr(2) << endl; // cdefgh
	cout << alphabet.substr(3) << endl; // defgh

	return 0;
}

size()를 사용하는 예시

#include <iostream>

using namespace std;

int main() {
	string alphabet = "abcdefgh";
	
    /* size()를 사용하여 뒤에서 원하는 만큼 가져온다 */
	cout << alphabet.substr(alphabet.size() - 1) << endl; //h
	cout << alphabet.substr(alphabet.size() - 2) << endl; //gh
	cout << alphabet.substr(alphabet.size() - 3) << endl; //fgh

	return 0;
}
profile
공부합니다

0개의 댓글