C++ string

2021. 3. 26. 15:27·C++/Library

string

  • <string> 라이브러리

basic_string

  • string, wstring 등의 문자열 클래스는 다음과 같이 basic_string 클래스 템플릿이 인스턴스화된 것이다.

    <xstring>

    using string  = basic_string<char, char_traits<char>, allocator<char>>;
    using wstring = basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t>>;
    #ifdef __cpp_lib_char8_t
    using u8string = basic_string<char8_t, char_traits<char8_t>, allocator<char8_t>>;
    #endif // __cpp_lib_char8_t
    using u16string = basic_string<char16_t, char_traits<char16_t>, allocator<char16_t>>;
    using u32string = basic_string<char32_t, char_traits<char32_t>, allocator<char32_t>>;

예제

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

  int     main()
  {
      using namespace std;

      const char* my_string = "my string";

      string  string1(my_string);
      string  string2(string1);
      string  string3(string1, 4);
      string  string4(string1, 4, 2);
      string  string5(my_string, 4);
      string  string6(10, 'A');

      vector<char> vec;
      for (auto& e : "Today is a good day")
          vec.push_back(e);

      string  string7(vec.begin(), vec.end());
      string  string8(vec.begin(), find(vec.begin(), vec.end(), 'a'));
      string  string9(std::to_string(1004));
      string9 += ' ' + std::to_string(3.14f);

      cout << "string1 : " << string1 << endl;
      cout << "string2 : " << string2 << endl;
      cout << "string3 : " << string3 << endl;
      cout << "string4 : " << string4 << endl;
      cout << "string5 : " << string5 << endl;
      cout << "string6 : " << string6 << endl;
      cout << "string7 : " << string7 << endl;
      cout << "string8 : " << string8 << endl;
      cout << "string9 : " << string9 << endl;
  }

  /* stdout stderr
  string1 : my string
  string2 : my string
  string3 : tring
  string4 : tr
  string5 : my s
  string6 : AAAAAAAAAA
  string7 : Today is a good day
  string8 : Tod
  string9 : 1004 3.140000
  */

getline

  • <iostream>을 include하면 <string>이 포함되는줄 알았는데, <string> 라이브러리를 include 하지 않으면 std::to_string(), std::getline()과 같은 함수를 쓸 수 없었다.

    • 즉 <iostream>에서 basic_string을 사용가능하도록 특정 라이브러리를 포함하지만, <string> 라이브러리가 포함되는 것은 아니다.
    #include <iostream>
    #include <string>
    
    int         main()
    {
        using namespace std;
    
        string buf;
    
        getline(cin, buf);
        cout << buf << endl;
    }
    
    /* stdin
    Hello World
    */
    
    /* stdout stderr
    Hello World
    */

대입, 교환, 덧붙이기, 삽입

  • 웬만한건 다 구현이 되어있다.

    #include <iostream>
    #include <string>
    
    int         main()
    {
      using namespace std;
    
      string str1("one");
      string str2;
    
      str2 = str1;
      cout << str2 << endl;
      str2 = "to";
      cout << str2 << endl;
      str2.insert(1, "w");
      cout << str2 << endl;
      str1 += ' ' + str2;
      str2.assign("three").append(" four").append(" five");
      cout << str2 << endl;
      str2.push_back('!');
    
      cout << "Before swap : " << str1 << ' ' << str2 << endl;
      std::swap(str1, str2);
      cout << "After swap : " << str1 << ' ' << str2 << endl;
    }
    
    /* stdout stderr
    one
    to
    two
    three four five
    Before swap : one two three four five!
    After swap : three four five! one two
    */

길이와 용량

  • vector와 비슷하게 길이(length)와 용량(capacity)을 따로 관리한다.

  • string::reserve() 함수는 최소한의 보장을 제공하므로 용량이 인자보다 더 클 수도 있다.

    #include <iostream>
    #include <string>
    
    int         main()
    {
      using namespace std;
    
      string my_str("012345678");
      string empty_str("");
    
      cout << "size : " << my_str.size() << endl;
      cout << "length : " << my_str.length() << endl;
      cout << "capacity : " << my_str.capacity() << endl;
      cout << "max_size : " << my_str.max_size() << endl;
    
      my_str.reserve(1000);
      cout << "capacity after reserve(1000) : " << my_str.capacity() << endl;
    
      cout << boolalpha;
      cout << "my_str is empty ? " << my_str.empty() << endl;
      cout << "empty_str is empty ? " << empty_str.empty() << endl;
    }
    
    /* stdout stderr
    size : 9
    length : 9
    capacity : 15
    max_size : 2147483647
    capacity after reserve(1000) : 1007
    my_str is empty ? false
    empty_str is empty ? true
    */

exception

  • std::exception으로 예외 처리를 받을 수 있다.

    • [] 연산자는 예외를 던지지 않는다.

      • 따라서 퍼포먼스가 중요한 경우 [] 연산자를 사용하는게 좋다.
    • string::at() 함수는 예외를 던진다.

      • 안정성이 중요한 경우 사용하는게 좋다.
    #include <iostream>
    #include <string>
    
    int         main()
    {
        using namespace std;
    
        string my_str("abcdefg");
    
        cout << my_str[0] << endl;
        cout << my_str[3] << endl;
    
        my_str[3] = 'Z';
        cout << my_str << endl;
    
        try
        {
            //my_str[100] = 'X';
            my_str.at(100) = 'X';
        }
        catch (std::exception& e)
        {
            cout << e.what() << endl;
        }
    }
    
    /* stdout stderr
    a
    d
    abcZefg
    invalid string position
    */

c-style string

  • char * 형태의 문자열로 변환하는 예제

    • string::c_str() 함수와 string::data() 함수를 통해 const char * 형태로 변환할 수 있다.

      • string::c_str() : null-terminated string이 아닌 경우, 해당 문자열을 복사하여 끝에 '\0'을 붙여준다.

      • string::data() : string 내부의 데이터를 그대로 리턴한다.

        • C++11부터는 string::data()도 '\0'를 붙여준다고 한다. 즉, string::c_str()과 같다고 생각하면 될 것 같다.

        • 또한 C++17부터 string::data()는 char * 형태로 반환된다고 한다.

        • 참고 : https://stackoverflow.com/questions/194634/string-c-str-vs-data

    #include <iostream>
    #include <string>
    
    int         main()
    {
      using namespace std;
    
      string my_str("abcdefg");
    
      cout << my_str.c_str() << endl;
      cout << int(my_str.c_str()[6]) << endl;
      cout << int(my_str.c_str()[7]) << endl;
    
      cout << my_str.data() << endl;
      cout << int(my_str.data()[6]) << endl;
      cout << int(my_str.data()[7]) << endl;
    }
    
    /* stdout stderr
    abcdefg
    103
    0
    */
  • string::copy() 함수로 char * 주소에 복사할 수도 있다.

    • 길이와 오프셋을 인자로 넣어야 한다.
    #include <iostream>
    #include <string>
    
    int         main()
    {
      using namespace std;
    
      string my_str("abcdefg");
    
      char buf[20] = { 0, };
    
      my_str.copy(buf, 5, 0);
      cout << buf << endl;
      my_str.copy(buf, 3, 1);
      cout << buf << endl;
    }
    
    /* stdout stderr
    abcde
    bcdde
    */

stringstream


wstring

저작자표시 (새창열림)

'C++ > Library' 카테고리의 다른 글

C++ wstring  (0) 2021.03.26
C++ sstream  (0) 2021.03.26
C++ STL 알고리즘 (Algorithms)  (0) 2021.03.26
C++ STL 반복자 (Iterators)  (0) 2021.03.26
C++ multimap  (0) 2021.03.26
'C++/Library' 카테고리의 다른 글
  • C++ wstring
  • C++ sstream
  • C++ STL 알고리즘 (Algorithms)
  • C++ STL 반복자 (Iterators)
Caniro
Caniro
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 분류 전체보기 (317)
      • Algorithm (13)
        • 알기 쉬운 알고리즘 (10)
        • Search (1)
        • Sort (2)
      • Arduino (0)
      • C++ (185)
        • Class (46)
        • Exception (6)
        • Library (51)
        • Overloading (10)
        • SmartPointer (5)
        • Syntax (33)
        • TBC++ (23)
        • Templates (9)
        • VisualStudio (2)
      • Embedded (1)
      • Git (4)
      • Java (5)
      • Linux (16)
        • Error (1)
        • Linux Structure (11)
      • MacOS (7)
      • OS (1)
        • Concurrency (1)
      • Python (21)
        • Class (1)
        • Function (2)
        • Syntax (17)
      • Raspberrypi (9)
      • Review (1)
      • Utility (12)
        • VSCode (5)
        • VirtualBox (3)
      • Web (8)
        • Nginx (1)
        • React (3)
        • Django (1)
      • Windows (20)
        • Registry (3)
        • WSL (1)
        • DeviceDriver (6)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    스프링 프레임워크 핵심 기술
    spring
    logi options
    EXCLUDE
    제외
    로지텍 마우스 제스처
    KakaoTalk
    맥북 카카오톡 알림 안뜸
    시스템 복구
    윈도우 명령어
    SFC
    vscode
    MacOS
    windows
    Solaris 10
    Workspace
    citrix workspace
    알림
    mspaint
    윈도우
    SunOS 5.1
    java
    백기선
    unix
    그림판
    Windows 11
    스프링
    dism
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Caniro
C++ string
상단으로

티스토리툴바