문자열은 문자들이 연속적으로 나열된 데이터다.
C++에서 문자열을 사용하기 위해 #include <string> 헤더를 포함해야 한다.
문자열 찾기(find)
문자열에서 특정 문자 또는 문자열을 찾을 때는 find() 메서드를 사용한다.
find 메서드는 find(찾으려는 문자열 또는 문자, 탐색 시작 위치)로 사용하고 만약 찾으면 문자열의 시작 위치를 인덱스로 반환하고 찾지 못했다면 string::npos라는 값을 반환한다.(탐색 시작 위치를 생략하면 처음부터 찾는다)
find()메서드의 시간 복잡도는 O(N), N은 검색 대상이 되는 원래 문자열의 길이다.
// 목적: 탐색 시작 위치를 지정하고, 찾지 못했을 경우 string::npos로 처리
#include <iostream>
#include <string>
using namespace std;
int main() {
string text = "hello world, hello C++";
size_t first_hello = text.find("hello");
size_t second_hello = text.find("hello", first_hello + 1); // 다음 "hello" 찾기
size_t not_found = text.find("Python");
cout << "첫 번째 hello 위치: " << first_hello << endl; // 출력결과: 첫 번째 hello 위치: 0
cout << "두 번째 hello 위치: " << second_hello << endl; // 출력결과: 두 번째 hello 위치: 13
if (not_found == string::npos) {
cout << "'Python'은 찾을 수 없습니다." << endl; // 출력결과: 'Python'은 찾을 수 없습니다.
}
return 0;
}
문자열 추가(append, +, +=)
문자열을 추가하려면 + 연산자 혹은 +=연산자를 사용해서 추가하거나 append() 메서드를 사용한다.
// 목적: 문자열에 다른 문자열을 결합하는 방법 (연결 연산자 +, +=)
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "APPLE";
string newStr = str + " PIE"; // + 연산자를 사용하여 결합
str += " JUICE"; // += 연산자를 사용하여 직접 결합
cout << "newStr: " << newStr << endl; // 출력결과: newStr: APPLE PIE
cout << "str: " << str << endl; // 출력결과: str: APPLE JUICE
return 0;
}
s.append(str)
str : 추가할 문자열
append의 시간 복잡도는 O(N+M), N은 기존 문자열 길이, M은 추가할 문자열 길이다.
// 목적: 문자열에 다른 문자열을 결합하는 방법 (append)
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "APPLE";
string newStr = str.append(" PIE"); // append() 메서드를 사용하여 결합
cout << "newStr: " << newStr << endl; // 출력 결과: newStr: APPLE PIE
return 0;
}
문자열 수정(replace)
문자열을 수정하려면 replace() 메서드를 사용한다.
[] 연산자를 사용해서 개별 문자에 접근하여 직접 변경할 수 있다.
// 목적: 문자열의 특정 위치 문자를 대괄호([])를 사용해 직접 수정
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "APPLE";
str[0] = 'M'; // 첫 글자를 A → M 으로 변경
cout << "수정된 문자열: " << str << endl; // 출력결과: 수정된 문자열: MPPLE
return 0;
}
replace() 메서드를 활용해 부분 문자열을 다른 문자열로 대체할 수 있다.
s.replace(pos, len, str)
pos : 시작 위치, len : 바꿀 길이, str : 대체할 문자열
replace의 시간 복잡도는 O(N - pos + M), N은 기존 문자열 길이, pos는 교체 시작 위치, M은 대체할 문자열 길이다.
// 목적: 문자열의 일부 구간을 다른 문자열로 대체하는 replace() 사용
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "APPLE";
str.replace(1, 3, "OAST"); // index 1부터 3개 문자(PPL)를 "OAST"로 대체
cout << "replace 후 문자열: " << str << endl; // 출력결과: replace 후 문자열: AOASTE
return 0;
}
부분 문자열 반환(substr)
문자열에서 부분 문자열을 반환하려면 substr() 메서드를 사용한다.
s.substr(pos, len)
pos : 시작 위치, len : 길이(생략 가능) len 생략 시 pos부터 문자열 끝까지 반환함.
substr의 시간 복잡도는 O(M), M은 반환할 부분 문자열의 길이다.
// 목적: substr()을 사용해 문자열에서 ID와 이름을 분리
#include <iostream>
#include <string>
using namespace std;
int main() {
string input = "2025_KIM";
string year = input.substr(0, 4); // "2025"
string name = input.substr(5); // "KIM"
cout << "년도: " << year << endl; // 출력결과: 년도: 2025
cout << "이름: " << name << endl; // 출력결과: 이름: KIM
return 0;
}
기타 문자열 메서드


'코딩테스트 공부' 카테고리의 다른 글
| 효율적인 코드 구현하기(벡터vs덱, 정렬이 필요없는데 정렬하는 경우, 특정 원소 찾기, 문자열 결합하기, auto& vs auto) (0) | 2025.09.29 |
|---|---|
| STL 사용하기(반복자, 컨테이너(vector, set, map), 알고리즘(sort, find, count, unique)) (0) | 2025.09.29 |
| 입력값 처리(숫자 반올림, 올림, 내림, 문자열 스트림, 진법 변환) (0) | 2025.09.29 |
| 자주 하는 실수(단락 평가, off by one, 0으로 나누기, 중간 값의 오버플로) (0) | 2025.09.26 |
| 알고리즘 효율(연산, 빅오 표기법) (0) | 2025.09.26 |