C++에서 가장 번거로운것 중 하나는 문자열 처리이다.
Tip!
1. getline은 앞뒤 개행문자까지 다 읽어온다.
string str;
getline(cin, str);
2. 문자 "0"를 int로 바꾸려면 '0'을 빼준다.
3. str.find(str2)를 했는데 못찾을 때, -1을 반환한다 생각해도 된다! (사실은 string::npos를 반환하지만)
4. str.find(str2, index)는 index 부터 탐색한다.
5. str.erase(index, size)는 삭제를 시작할 index와 크기이다.
※ 문자열 자르기
Case 1) string 클래스 사용할 때
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world, Korea";
size_t prev = 0;
size_t curr = str.find(','); //못찾으면 npos 반환
while (curr != string::npos) {
string substring = str.substr(prev, curr - prev);
cout << substring << ' ';
prev = curr + 1;
curr = str.find(',', prev);
}
cout << str.substr(prev, curr - prev);
}
Case 2) sstream 클래스 이용할 때
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str = "Hello world and Korea";
istringstream iss(str);
string token;
while (getline(iss, token, " ")){
cout << token << endl;
}
}
Case 3) 특정 문자열 찾기
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello my name is V2LLAIN";
string word = "V2";
int pos = str.find(word);
while (pos != string::npos) {
cout << str.substr(pos, word.size()) << endl;
pos = str.find(word, pos+word.size());
}
}
※ 가장 많이 출제되는 코딩테스트 유형들
1. DFS / BFS
2. 문자열
3. 구현
4. DP
'Algorithms > Algorithm skill' 카테고리의 다른 글
this.algorithm(5). C 표준 라이브러리 <cmath> ★★☆ (0) | 2022.11.03 |
---|---|
this.algorithm(4). 중복된 원소제거, unique() ★★★ (0) | 2022.11.03 |
this.algorithm(3). C++ 코테에서 시간초과에 잘 안걸리는 함수 (0) | 2022.11.03 |
this.algorithm(2). merge() 함수, copy() max(), min() 함수 ★★★★★ (0) | 2022.11.02 |
코딩테스트를 위한 필수 STL 총정리 (★★★★★★★) (0) | 2022.10.29 |