[C++ STL] 코딩테스트를 위한 string

2023. 10. 16. 15:40·C++/C++ STL

◆string 클래스의 정의

어려워서 추후 글 작성 예정.

구문도 최소화 하겠습니다.

 

◆string 클래스의 구문

typedef basic_string<char, char_traits<char>, allocator<char>> string;

 

◆string 함수

 

str.getline()

: 입력 스트림에서 문자열을 한 줄씩 추출합니다.

: 매개 변수로 instream, str, delimeter가 있는데 delimeter를 쓰고 안쓰고로 나뉜다.

// (1) delimiter as parameter
template <class CharType, class Traits, class Allocator>
basic_istream<CharType, Traits>& getline(
    basic_istream<CharType, Traits>& in_stream,
    basic_string<CharType, Traits, Allocator>& str,
    CharType delimiter);

template <class CharType, class Traits, class Allocator>
basic_istream<CharType, Traits>& getline(
    basic_istream<CharType, Traits>&& in_stream,
    basic_string<CharType, Traits, Allocator>& str,
    const CharType delimiter);

// (2) default delimiter used
template <class CharType, class Traits, class Allocator>
basic_istream<CharType, Traits>& getline(
    basic_istream<CharType, Traits>& in_stream,
    basic_string<CharType, Traits, Allocator>& str);

template <class Allocator, class Traits, class Allocator>
basic_istream<Allocator, Traits>& getline(
    basic_istream<Allocator, Traits>&& in_stream,
    basic_string<Allocator, Traits, Allocator>& str);

1. delimeter을 쓰지 않았을 경우

  • 한 줄을 기준으로 입력을 받는다.

2. delimeter을 쓴 경우

  • delimeter을 기준으로 입력을 받는다.

예제 코드) [MSDN에서 수정] 2가지 방법으로  EOF를 받을 때까지 입력을 받아주는 코드입니다.

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

using namespace std;

int main()
{
    string str;
    vector<string> v1;
    cout << "Enter a sentence, press ENTER between sentences. (Ctrl-Z to stop): " << endl;
    while (getline(cin, str)) {
        v1.push_back(str);
    }
    cout << "The following input was stored with newline delimiter:" << endl;
    for (const auto& p : v1) {
        cout << p << endl;
    }
    cin.clear();

    vector<string> v2;
    cout << "Enter a sentence, press whitespace between sentences. (Ctrl-Z to stop): " << endl;
    while (getline(cin, str, ' ')) {
        v2.push_back(str);
    }
    cout << "The following input was stored with whitespace as delimiter:" << endl;
    for (const auto& p : v2) {
        cout << p << endl;
    }
}

 

실행 결과)

실행 결과

 

stod()

: 문자 시퀀스를 double으로 변환합니다.

str은 문자열, idx는 변환되지 않은 첫 번째 문자의 인덱스 값입니다.

idx의 의미는 stod에서 "1.0str"에서 "1.0"만을 숫자로 인식하기 때문에 s의 인덱스 값을 idx에 저장합니다. (예제에서 보충)

double stod(
    const string& str,
    size_t* idx = 0);

double stod(
    const wstring& str,
    size_t* idx = 0);

 

예제 코드) stod 함수를 사용하여 return과 idx의 값을 확인하는 반복문이다.

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

using namespace std;

int main()
{
    string str;
    string str2;
    cout << "Enter a string. (Ctrl-Z to stop): " << endl;
    size_t idx = 10;
    while (getline(cin, str))
    {
        cout << "stod : " << stod(str, &idx) << endl;
        cout << "idx : " << idx << endl << endl;
        cout << "Enter a string. (Ctrl-Z to stop): " << endl;
        // 반복문에 이상 발생시 아래 구문 추가 (Debug : <error reading variable : 주소가 0x0이고 길이가 0이 아닌 레이지 문자열을 만들 수 없습니다.> )
        // str = "a";
    }
}

 

실행 결과)

보이는 것과 같이 숫자로 변환이 가능한 부분까지만 숫자로 변환하여 리턴한뒤, idx는 변환되지 않은 첫 번째 문자의 인덱스 값으로 초기화가 됨을 확인 할 수 있다.

 

stof()

: 문자 시퀀스를 float로 변환합니다.

float stof(
    const string& str,
    size_t* idx = 0);

float stof(
    const wstring& str,
    size_t* idx = 0);

 

stoi()

: 문자 시퀀스를 정수로 변환합니다.

여기서 base는어떤 진수로 변환할지를 정하는 역할을 합니다.

int stoi(
    const string& str,
    size_t* idx = 0,
    int base = 10);

int stoi(
    const wstring& str,
    size_t* idx = 0,
    int base = 10);

 

stol()

: 문자 시퀀스를 long으로 변환합니다.

long stol(
    const string& str,
    size_t* idx = 0,
    int base = 10);

long stol(
    const wstring& str,
    size_t* idx = 0,
    int base = 10);

 

stold(), stoll(), stoul(), stoull()

: 문자 시퀀스를 자료형으로 변환합니다. (원리는 같으니 생략하겠습니다.

class TtoT2(
    const string& str,
    size_t* idx = 0,
    int base = 10);

 

swap()

: 두 문자열의 문자 배열을 교환합니다.

template <class Traits, class Allocator>
void swap(basic_string<CharType, Traits, Allocator>& left, basic_string<CharType, Traits, Allocator>& right);

MSDN 예제)

// string_swap.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;
   // Declaring an object of type basic_string<char>
   string s1 ( "Tweedledee" );
   string s2 ( "Tweedledum" );
   cout << "Before swapping string s1 and s2:" << endl;
   cout << "The basic_string s1 = " << s1 << "." << endl;
   cout << "The basic_string s2 = " << s2 << "." << endl;

   swap ( s1 , s2 );
   cout << "\nAfter swapping string s1 and s2:" << endl;
   cout << "The basic_string s1 = " << s1 << "." << endl;
   cout << "The basic_string s2 = " << s2 << "." << endl;
}

결과)

이미지 입니다.

to_string(), to_wstring

: 값을 string로 변환합니다.

string to_string(int value);
string to_string(unsigned int value);
string to_string(long value);
string to_string(unsigned long value);
string to_string(long long value);
string to_string(unsigned long long value);
string to_string(float value);
string to_string(double value);
string to_string(long double value);

 

 

◆string 연산자

operator+

: 두 문자열 개체를 연결합니다.

operator!=

: 연산자의 좌변에 있는 문자열 개체가 우변에 있는 문자열 개체와 같지 않은지 테스트합니다.

operator<

: 연산자의 좌변에 있는 문자열 개체가 우변에 있는 문자열 개체보다 작은지 테스트합니다.

operator>>

: 입력 스트림에서 문자열을 읽는 템플릿 함수입니다.

template <class CharType, class Traits, class Allocator>
basic_istream<CharType, Traits>& operator>>(
    basic_istream<CharType, Traits>& _Istr,
    basic_string<CharType, Traits, Allocator>& right);

 

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

[C++ STL] 코딩테스트를 위한 basic_string  (0) 2023.10.18
[C++ STL] 코딩테스트를 위한 algorithm  (1) 2023.10.16
[C++ STL] 코딩테스트를 위한 vector  (1) 2023.10.14
'C++/C++ STL' 카테고리의 다른 글
  • [C++ STL] 코딩테스트를 위한 basic_string
  • [C++ STL] 코딩테스트를 위한 algorithm
  • [C++ STL] 코딩테스트를 위한 vector
메카인
메카인
  • 메카인
    메카인의 지식창고
    메카인
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 코딩 공부
        • TIL(Today I Learn)
        • TIL
        • 백준(C++)
        • Python
        • 알고리즘
        • 프로젝트 회고
      • C++
        • C++
        • C++ STL
        • C,C++ mCoding yotube
      • 게임개발
        • 언데드서바이벌_골드메탈_클론코딩
        • 3D_골드메탈_클론코딩
        • 유니티_문제해결
        • 게임 수학
      • Unreal 공부
        • UE5 GameDev
        • Unreal Engine 4 C++ The Ult..
      • 교재 문제 풀이
        • 운영체제
      • 정보처리기사
        • 정처기 요약
        • 정처기 오답노트
      • 학교수업
        • 데이터베이스
        • 프로그래밍 언어론
        • 리눅스 시스템
        • 네트워크
      • 일상
        • 주식
        • 독서
      • (비공개 전용)
        • memory
        • Build
        • OOP
        • Smart Pointer
        • lamda
        • 게임 수학
        • 모던 C++
        • 모던 C++ STL
        • 모던 C++ Concurrency, Paralle..
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글쓰기
    • 블로그 관리
  • 링크

  • 공지사항

    • 공지사항 - 인생과 블로그의 목표
  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
메카인
[C++ STL] 코딩테스트를 위한 string
상단으로

티스토리툴바