C++ string_view | "문자열 뷰" C++17 가이드
이 글의 핵심
C++ string_view에 대해 정리한 개발 블로그 글입니다. #include <string_view> using namespace std;
string vs string_view
#include <string_view>
using namespace std;
// string (복사)
void print1(string s) {
cout << s << endl; // 복사 발생
}
// string_view (복사 없음)
void print2(string_view sv) {
cout << sv << endl; // 복사 없음
}
int main() {
string s = "Hello World";
print1(s); // 복사
print2(s); // 복사 없음
}
기본 사용법
string_view sv1 = "Hello"; // 문자열 리터럴
string s = "World";
string_view sv2 = s; // string
char arr[] = "Test";
string_view sv3 = arr; // char 배열
cout << sv1 << endl;
cout << sv2 << endl;
cout << sv3 << endl;
부분 문자열
string_view sv = "Hello World";
// substr (복사 없음)
string_view sub = sv.substr(0, 5);
cout << sub << endl; // Hello
// 범위
cout << sv.substr(6) << endl; // World
실전 예시
예시 1: 토큰화
vector<string_view> split(string_view sv, char delim) {
vector<string_view> result;
size_t start = 0;
size_t end = sv.find(delim);
while (end != string_view::npos) {
result.push_back(sv.substr(start, end - start));
start = end + 1;
end = sv.find(delim, start);
}
result.push_back(sv.substr(start));
return result;
}
int main() {
string text = "apple,banana,cherry";
for (string_view token : split(text, ',')) {
cout << token << endl;
}
}
예시 2: 파싱
optional<int> parseInt(string_view sv) {
// 공백 제거
while (!sv.empty() && isspace(sv.front())) {
sv.remove_prefix(1);
}
while (!sv.empty() && isspace(sv.back())) {
sv.remove_suffix(1);
}
if (sv.empty()) {
return nullopt;
}
try {
return stoi(string(sv));
} catch (...) {
return nullopt;
}
}
int main() {
cout << parseInt(" 123 ").value_or(0) << endl; // 123
cout << parseInt("abc").value_or(0) << endl; // 0
}
예시 3: 문자열 비교
bool startsWith(string_view sv, string_view prefix) {
return sv.substr(0, prefix.size()) == prefix;
}
bool endsWith(string_view sv, string_view suffix) {
if (suffix.size() > sv.size()) return false;
return sv.substr(sv.size() - suffix.size()) == suffix;
}
int main() {
string_view sv = "hello.txt";
cout << startsWith(sv, "hello") << endl; // 1
cout << endsWith(sv, ".txt") << endl; // 1
}
예시 4: 로그 파서
struct LogEntry {
string_view timestamp;
string_view level;
string_view message;
};
optional<LogEntry> parseLogLine(string_view line) {
// [2026-03-11 10:30:00] [INFO] 메시지
if (line.size() < 2 || line[0] != '[') {
return nullopt;
}
size_t pos1 = line.find(']');
if (pos1 == string_view::npos) return nullopt;
string_view timestamp = line.substr(1, pos1 - 1);
line.remove_prefix(pos1 + 2);
if (line.empty() || line[0] != '[') return nullopt;
size_t pos2 = line.find(']');
if (pos2 == string_view::npos) return nullopt;
string_view level = line.substr(1, pos2 - 1);
string_view message = line.substr(pos2 + 2);
return LogEntry{timestamp, level, message};
}
int main() {
string log = "[2026-03-11 10:30:00] [INFO] 서버 시작";
if (auto entry = parseLogLine(log)) {
cout << "시간: " << entry->timestamp << endl;
cout << "레벨: " << entry->level << endl;
cout << "메시지: " << entry->message << endl;
}
}
수정 불가
string_view sv = "Hello";
// ❌ 수정 불가
// sv[0] = 'h'; // 에러
// ✅ string으로 변환 후 수정
string s(sv);
s[0] = 'h';
cout << s << endl; // hello
자주 발생하는 문제
문제 1: 댕글링 참조
// ❌ 위험
string_view getView() {
string s = "Hello";
return s; // s 소멸, 댕글링!
}
// ✅ string 반환
string getString() {
string s = "Hello";
return s;
}
// ✅ 문자열 리터럴
string_view getLiteral() {
return "Hello"; // OK (리터럴은 프로그램 종료까지 유효)
}
문제 2: 수명 관리
// ❌ 위험
string_view sv;
{
string s = "Hello";
sv = s;
} // s 소멸
cout << sv << endl; // 댕글링!
// ✅ 수명 보장
string s = "Hello";
string_view sv = s;
cout << sv << endl;
문제 3: null 종료
// ❌ null 종료 보장 안됨
string_view sv = "Hello";
const char* cstr = sv.data(); // null 종료 보장 안됨!
// ✅ string 변환
string s(sv);
const char* cstr = s.c_str(); // null 종료 보장
성능 비교
#include <chrono>
void benchmarkString(const string& s) {
// 복사 발생
}
void benchmarkStringView(string_view sv) {
// 복사 없음
}
int main() {
string s(10000, 'x');
auto start = chrono::high_resolution_clock::now();
for (int i = 0; i < 100000; i++) {
benchmarkString(s);
}
auto end = chrono::high_resolution_clock::now();
cout << "string: " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << "ms" << endl;
start = chrono::high_resolution_clock::now();
for (int i = 0; i < 100000; i++) {
benchmarkStringView(s);
}
end = chrono::high_resolution_clock::now();
cout << "string_view: " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << "ms" << endl;
}
FAQ
Q1: string_view는 언제 사용하나요?
A:
- 읽기 전용 문자열 매개변수
- 부분 문자열 추출
- 성능 최적화
Q2: string vs string_view?
A:
- string: 소유, 수정 가능
- string_view: 뷰, 읽기 전용
Q3: 성능 이점은?
A: 복사 없음. 큰 문자열일수록 효과 큼.
Q4: 수명 관리는?
A: 원본 문자열이 유효한 동안만 사용.
Q5: null 종료는?
A: 보장 안됨. C 함수에 전달 시 주의.
Q6: string_view 학습 리소스는?
A:
- cppreference.com
- “C++17: The Complete Guide”
- “Effective Modern C++“
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ 정규표현식 | “regex” 완벽 가이드
- C++ string | “문자열 처리” 완벽 가이드 [실전 함수 총정리]
- C++ Expression Templates | “지연 평가” 고급 기법
관련 글
- C++ string vs string_view |