본문 바로가기

C++/공부 정리

파싱

length(), size() : 길이 출력 가능

 

strlen()과 length()의 속도가 다름 

for문에 strlen을 사용 시 계속 함수를 호출하므로 속도에 영향을 줌.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string words;
    cin >> words;
    for(int i=words.length()-1; i>=0; i--)
        cout << words[i];
    return 0;
}

String class에 length()라는 메서드가 있는 것임

 

파싱의 이유: 실제 데이터에서 원하는 값을 찾기 위해

find로 인덱스를 찾고 substr로 원하는 값 추출

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string  a;
    cin >> a;
    int g1 = a.find('[');
    int g2 = a.find(']');
    // int g2 = a.find(']', a + 1);
    // a 다음 인덱스부터 탐색시켜 속도를 빠르게 함
    cout << a.substr(g1 + 1, g2 - g1 -1);
    return 0;
}
#include <iostream>
#include <string>
using namespace std;

int main()
{
    //c언어 스타일 문자열을 string 클래스로 바꿔주는 법
    char buf[10] = "WEQ";
    string a = buf;
    
    // 그 반대의 경우, string 클래스 안에 c_str() 메서드 사용
    strcpy(buf,a.c_str());
    printf("%s", a.c_str());
    
    return 0;
}
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string a[4] = {
        "ABCQ",
        "B[4]R",
        "CCDA",
        "BT[15]"
    };
    for(int i=0; i<4; i++)
    {
        int start = a[i].find('[');
        if(start == -1) continue;
        
        int end = a[i].find(']', start + 1);
        
        cout << a[i].substr(start + 1, end - start - 1) << '\n';
    }
    
    return 0;
}

보완할 점: 여러번 반복하는 동작은 함수로 빼서 해주는 것이 좋음.

 

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s = "2423";
    int i = stoi(s);
    
    string b = to_string(i);
    cout << i << '\n' << b;
    
    return 0;
}

stoi : 문자열을 숫자로

to_string() : 숫자를 문자열로

 

 

45와 9994를 추출한 뒤 합을 구하기

#include <iostream>
#include <string>
using namespace std;


int getNum(string s)
{
    int i = 0, result = 0;
    while(i < s.length())
    {
        if(s.find('[') == -1) return -1;
        int start = s.find('[', i);
        int end = s.find(']', start + 1);
        int size = end - start - 1;
        
        i = end + 1;
        string c = s.substr(start + 1, size);
        result += stoi(c);
    }
    return result;
}
int main()
{
    // 파싱 문제의 경우 하드 코딩한 뒤 나중에 입력으로 바꿔주는 것이 편함
    string s = "BAB123";
    cout << getNum(s);

    
    return 0;
}

 

문자열에서 특정 문자열 찾기

#include <iostream>
#include <string>
using namespace std;


int getNum(string s)
{
    int i = 0, result = 0;
    while(i < s.length())
    {
        int index = s.find("ABC", i);
        if(index != -1)
        {
            result++;
            i = index + 1;
        }
        else
            break;
        
    }
    return result;
}
int main()
{
    // 파싱 문제의 경우 하드 코딩한 뒤 나중에 입력으로 바꿔주는 것이 편함
    string s = "ABCAAABCAAABCA";
    cout << getNum(s);

    
    return 0;
}

여기서 index를 사용하지 않고 i를 그대로 사용해도 가능하다.

 

gold 총 갯수 세기

#include <iostream>
#include <string>
using namespace std;

int find(string s)
{
    int i = -1, result = 0;
    while(1)
    {
        i = s.find("GOLD", i + 1);
        if(i == -1) break;
        result++;
        i++;
    }
    
    return result;
}
int main()
{
    string mine[4] = {
        "GOLDABGOLD",
        "GOLDTTTT",
        "AGOLDGOLD",
        "GOLDTTTT"
    };
    int cnt = 0;
    for(int i=0; i<4; i++)
    {
        cnt += find(mine[i]);
    }
    cout << cnt;
    return 0;
}