Blog Content

    티스토리 뷰

    string class

    #include <string> 사용


    1. 공백 문자까지 입력 받을 경우 (getline)

    getline(입력방식, 입력버퍼시작주소, 구분문자)


    1
    2
    3
    string name;
    getline(cin, name, '\n');
    cout << name << endl;
    cs


    2. 문자열 확장 (append)

    .append("추가 문자열")


    1
    2
    3
    4
    string s = "Hello ";
    += "Happy ";
    s.append("World!");
    cout << s << endl;
    cs



    3. 문자열 길이 (length) 

    length 메서드는 문자열의 길이를 반환한다. ('\n'은 포함하지 않는다)

    .length()


    1
    2
    string s = "Hello";
    cout << s.length() << endl// 5
    cs


    4. 문자열 인덱싱 (at)

    문자열의 n번째를 반환한다.

    .at(인덱스넘버)


    1
    2
    3
    string s = "Hello";
    cout << s[0<< endl// H
    cout << s.at(0<< endl// H
    cs


    5. 문자열 삽입 (insert)

    .insert(추가할 문자열의 시작인덱스, 추가할 문자열)


    1
    2
    string s = "Hello World!";
    cout << s.insert(6"Happy "<< endl;
    cs



    6. 문자열 대체 (replace)

    .replace(시작인덱스, 끝인덱스+1, 대체문자열)


    1
    2
    string s = "Hello World!";
    cout << s.replace(05"Bye"<< endl;
    cs



    7. 문자열 검색 (find)

    탐색문자열의 시작인덱스를 반환 없다면 -1을 반환

    .find("탐색문자열")


    1
    2
    3
    string s = "Hello World!";
    int num = s.find("Hello");
    cout << num << endl// 0
    cs


    8. 문자열 비교 (compare)

    같으면 1

    대상문자열이 크면 1

    비교문자열이 크면 -1 을 반환

    대상문자열.compare(비교문자열)


    1
    2
    3
    4
    5
    6
    7
    string a = "abc";
    string b = "abc";
    string c = "abd";
     
    cout << a.compare(b) << endl// 0
    cout << a.compare(c) << endl// -1
    cout << c.compare(a) << endl// 1
    cs



    Comments