250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/CPP] 17.04. 문자 접근과 배열로 전환 본문

C++/따배C++ 17강 String

[C++/CPP] 17.04. 문자 접근과 배열로 전환

polarcompass 2021. 12. 16. 07:52
728x90
#include<iostream>
#include<string>
#include<vector>

using namespace std;

int main()
{
    string my_str("abcdefg");
    {
        cout << my_str[0] << endl;
        cout << my_str[3] << endl;

        my_str[3] = 'Z';

        cout << my_str << endl;
    }

    {
        try
        {
            // []: 예외처리 안됨( 속도가 느려져서 )
            // .at() : 예외 처리됨.

            // my_str[100] = 'X'; // 속도가 중요할때
            my_str.at(100) = 'X'; // 안정성이 중요할때
            cout << my_str << endl;
        }
        catch (std::exception &e)
        {
            cout << "catch: " << e.what() << endl;
        }
    }

    {
        // c-style 문자
        string my_str("abcdefg");

        cout << my_str.c_str() << endl;

        // c_str() == data() 거의 같은 함수임.
        // const char *arr = my_str.c_str(); // 뒤에 null 문자를 더함.
        const char *arr = my_str.data();
        
        cout << (int)arr[6] << endl;
        cout << (int)arr[7] << endl;
    }

    {
        string my_str("abcdefg");
        char buf[20];

        my_str.copy(buf, 5, 1); // copy(변수, 집어넣을 문자 개수, offset)

        buf[5] = '\0'; // null character

        cout << buf << endl;
    }

    return 0;
}
728x90