c++

STL::string 정리

moongi 2023. 10. 31. 19:44
반응형

* 하나의 sentence로 이루어진 문장에서 단어별로 분리하기

 

#include <iostream>
using namespace std;

int main(int argc, char const *argv[])
{
    string a = "It is time to study", res;

    int pos, max = INT_MIN;
    while ((pos = a.find(' ')) != string::npos)
    {
        string tmp = a.substr(0, pos);
        int len = tmp.size();
        if (len > max)
        {
            max = len;
            res = tmp;
        }

        cout << tmp << '\n';
        a = a.substr(pos + 1);
    }

    if (a.size() > max)
    {
        max = a.size();
        res = a;
    }

    cout << res << '\n';

    return 0;
}

 

<algorithm> 헤더파일을 통해서 string 안에 소문자, 대문자, 숫자를 구별할 수 있다.

substr(pos, cnt) : pos부터 cnt개수만큼 꺼내온다.

vector와 같이 push_back(), pop_back()로 값을 넣어줄 수 있다.

clear(): string을 비운다.

 

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main(int argc, char const *argv[])
{
    string a = "Time is 2023Year 10Month";
    cout << a.size() << '\n';

    for (int i = 0; i < a.size(); i++)
    {
        cout << a[i] << " ";
    }
    cout << '\n';

    for (int i = 0; i < a.size(); i++)
    {
        if (isupper(a[i]))
        {
            cout << a[i] << " ";
        }
    }
    cout << '\n';

    for (int i = 0; i < a.size(); i++)
    {
        if (islower(a[i]))
        {
            cout << a[i] << " ";
        }
    }
    cout << '\n';

    for (int i = 0; i < a.size(); i++)
    {
        if (isdigit(a[i]))
        {
            cout << a[i] << " ";
        }
    }
    cout << '\n';

    cout << a.find('Y') << '\n';

    a.push_back('a');
    cout << a << '\n';

    a.pop_back();
    cout << a << '\n';

    a += " 31day";
    cout << a << '\n';

    cout << a.substr(8) << '\n';
    cout << a.substr(8, 4) << '\n';
    a.clear();

    cout << a << '\n';

    return 0;
}
반응형