🌍 C++ Study/C++ 기초
C++ string 부분 문자열 구하기 string::substr
맨텀
2024. 11. 16. 16:31
1. string::substr
cplusplus : substr
https://cplusplus.com/reference/string/string/substr/
첫번째 인자로 시작 위치, 생략시 첫번째 위치이다.
두번째 인자로 길이를 받는다. 생략시 끝까지 추출한다.
string substr (size_t pos = 0, size_t len = npos) const;
std::string text = "Hello, World!";
std::string sub = text.substr(7, 5); // 7번 인덱스부터 길이 5만큼 추출 ("World")
std::string::find와 같이 사용하면?
특정 문자열을 찾아서 추가 처리하는 방식으로 사용 가능하다.
#include <iostream>
#include <string>
int main() {
std::string text = "C++ is a powerful language.";
size_t pos = text.find("powerful"); // "powerful"의 시작 위치 찾기
if (pos != std::string::npos) {
std::string sub = text.substr(pos, 8); // "powerful"의 시작 위치에서 길이 8 추출
std::cout << "Found substring: " << sub << std::endl;
} else {
std::cout << "Substring not found!" << std::endl;
}
return 0;
}
2. 방법2 : 복사 생성자를 활용하기
string의 생성자 중 일부는 부분 문자열을 생성할 수 있도록 선언되어있다.
2-1) 원본 string, 시작위치, 길이로 복사생성자.
std::string(const std::string& str, size_type pos, size_type count = npos);
std::string substring(original, 7, 5); // 시작 위치 7, 길이 5
2-2) 시작 이터레이터, 끝 이터레이터로 복사 생성자
std::string(InputIt first, InputIt last);
string sub(my_string.begin(), my_string.begin() + is_prefix.size());
3. 방법3 : Range-based syntax (C++ 20)
std::string_view sv = original;
auto substring = sv{7, 12}; // 범위 기반