C++ string

2021. 3. 26. 15:27·SW개발/C++
목차
  1. basic_string
  2. 예제
  3. getline
  4. 대입, 교환, 덧붙이기, 삽입
  5. 길이와 용량
  6. exception
  7. c-style string
  8. stringstream
  9. wstring
반응형

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

반응형
저작자표시 (새창열림)

'SW개발 > C++' 카테고리의 다른 글

C++ wstring  (0) 2021.03.26
C++ sstream  (0) 2021.03.26
따라하며 배우는 C++ 17장  (0) 2021.03.26
C++ STL 알고리즘 (Algorithms)  (0) 2021.03.26
C++ STL 반복자 (Iterators)  (0) 2021.03.26
  1. basic_string
  2. 예제
  3. getline
  4. 대입, 교환, 덧붙이기, 삽입
  5. 길이와 용량
  6. exception
  7. c-style string
  8. stringstream
  9. wstring
'SW개발/C++' 카테고리의 다른 글
  • C++ wstring
  • C++ sstream
  • 따라하며 배우는 C++ 17장
  • C++ STL 알고리즘 (Algorithms)
Caniro
Caniro
MinimalismCaniro 님의 블로그입니다.
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 전체보기 (319)
      • SW개발 (268)
        • Java Spring (6)
        • C++ (186)
        • Python (21)
        • Linux (16)
        • 알고리즘 (13)
        • Git (4)
        • Embedded (1)
        • Raspberrypi (9)
        • React (3)
        • Web (2)
        • Windows Device Driver (6)
      • IT(개발아님) (46)
        • Windows (26)
        • MacOS (7)
        • Utility (11)
      • 챗봇 짬통 (0)
      • 일상 (2)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

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

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.