daramG 2022. 3. 31. 23:49

문자열에 대한 학습

 

공백까지 입력받는 방법

getline(cin, sentence);

 

 

문자열 치환 함수

 

문자열.replace(시작 위치, 길이, 치환 문자열);

sentence.replace(0, 2, ee);

 

regex_replace.(대상 문자열,  regex(정규식), 치환 문자열)

#include <regex> 사용

regex_replace("aabbccddd", regex("c"), "z");
// aabbzzddd 가 된다.

 

백준 문제풀이

 

5622번 문제 : 다이얼

문제 :

 

소스코드 :

 

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    vector<int> v = {3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,8,9,9,9,10,10,10,10};
    string sen;
    cin >> sen;
    
    int sum = 0;
    for(int i=0; sen[i]!='\0'; i++) {
        sum += v.at(sen[i] - 'A');
    }
    
    cout << sum;
    
    return 0;
}

 

if문으로 노가다하는 코드를 작성하다가 취소하고 새로 작성했다.

 

 

2941번 문제 : 크로아티아 알파벳

문제 :

 

소스코드 :

#include <iostream>
#include <string>
#include <vector>
#include <regex>

using namespace std;

string search(string sen) {
    vector<string> v = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
    for(int i=0; i<v.size(); i++) {
        sen = regex_replace(sen, regex(v[i]), "@");
    }
    return sen;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    string sen;
    getline(cin, sen);
    
    string sen2;
    sen2 = search(sen);
    
    cout << sen2.length();
    
    return 0;
}

 

1316번 문제 : 그룹 단어 체커

문제 :

 

소스코드 :

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int check(string sen) {
    vector<int> v;
    v.assign(26, 0);
    int dex;
    bool same = false;
    
    dex = sen[0] - 'a';
    v[dex] += 1; 
    
    for(int i=1; i<sen.length(); i++) {
        if (sen[i-1] != sen[i]) same = false;
        else if (sen[i-1] == sen[i]) same = true;
        
        dex = sen[i] - 'a';
        v[dex] += 1;
        
        if (same == false && v[dex] > 1) {
            return 0;
        }
    }
    return 1;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    int n;
    string sen;
    int groupCount = 0;
    cin >> n;
    for(int i=0; i<n; i++) {
        cin >> sen;
        groupCount += check(sen);
    }

    cout << groupCount;
    
    return 0;
}

 

벡터 a-z의 개수를 저장하는 벡터 {0, 0, 0, ... ,0} 을 만들고 각 알파벳을 읽으면서 벡터값을 올린다.

예를 들면 c를 입력받으면 {0, 0, 1, 0, 0, ...} 이렇게 된다.

 

이미 나왔던 알파벳이 떨어져서 나온 문자열을 구하기 위해서

읽는 문자열이 이전 값과 다르고, 벡터가 1 이상일 경우로 정의하고 구했다.

 

 

 

지금까지 문자열까지 단계별 문제를 풀어보았다.