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());
    }
}

 

 

출처: https://velog.io/@siyeonkm/cpp-%EC%BD%94%ED%85%8C%EC%97%90%EC%84%9C-%EC%95%8C%EC%95%84%EC%95%BC%ED%95%98%EB%8A%94%EA%B2%83%EB%93%A4

 

 

 

 

 

 

※ 가장 많이 출제되는 코딩테스트 유형들

1. DFS / BFS

2. 문자열

3. 구현

4. DP

https://velog.io/@pppp0722/%EC%BD%94%EB%94%A9%ED%85%8C%EC%8A%A4%ED%8A%B8-%EB%AC%B8%EC%A0%9C-%EC%9C%A0%ED%98%95-%EC%A0%95%EB%A6%AC

 

 

 

 

 

 

 

 

 

 

 

 

 

 

+ Recent posts