Study/C++

[C++]04.3 복합데이터형 - String클래스

SigmoidFunction 2023. 3. 10. 14:25
728x90

string클래스는 배열보다 사용하기가 쉽고 하나의 데이터형으로 나타낸다.

 

// strtyp1.cpp -- C++ string클래스를 사용한다.
#include <iostream>
#include <string>       // string클래스를 사용하기 위해
int main()
{
    using namespace std;
    char charr1[20];               // 빈배열 생성
    char charr2[20] = "jaguar";    // 초기화된 배열 생성
    string str1;                   // 빈 string 객체 생성
    string str2 = "panther";       // 초기화된 string 객체 생성

    cout << "Enter a species of animal in the cat family: ";
    cin >> charr1;
    cout << "Enter another species of animal in the cat family: ";
    cin >> str1;
    cout << "The animals below are all cats: \n";
    cout << charr1 << " " << charr2 << " "
        << str1   << " " << str2          // 출력을 위해 cout을 사용한다
        << endl;
    cout << "The third letter from the " << charr2 << ": "
         << charr2[2] << endl;
    cout << "The third letter from the " << str2 << ": "
         << str2[2] << endl;               // 배열 표기를 사용
 return 0;   
}

// Enter a species of animal in the cat family: lion
// Enter another species of animal in the cat family: tiger
// The animals below are all cats:     
// lion jaguar tiger panther
// The third letter from the jaguar: g 
// The third letter from the panther: n

string객체와 문자 배열을 같은 방식으로 사용할 수 있다.

 

  • C스타일의 문자열로 string 초기화가능
  • cin을 사용하여 string객체에 키보드 입력 저장 가능
  • cout을 사용하여 string 객체를 출력 가능
  • 배열 표기를 사용하여 string객체의 개별 문자들에 접근할 수 있다.

string과 배열의 차이는 단순 변수로 선언하는 것

이는 string클래스가 자동으로 크기를 처리하도록 한다.

str1은 0의 길이를 넣지만 값을 넣게 되면 크기를 자동 조정하게 된다.

 

    char charr1[20];               
    char charr2[20] = "jaguar";    
    string str1;                   
    string str2 = "panther";  
    
    charr1 = charr2;   // 안됨. 배열 대입 X
    str1 = str2		// 가능. 객체 대입 O
    
    string str2;
    str3 = str1 + str2; 	// 결합된 두 객체를 str3에 저장
    str1 += str2;		// str1 끝에 str2를 추가

 

 

// strtype2.cpp -- 대입, 추가, 첨부
#include <iostream>
#include <string>
int main()
{
    using namespace std;
    string s1 = "penguin";
    string s2, s3;

    cout << "You can substitute a string object for a string object: s2 = s1\n";
    s2 = s1;
    cout << "s1: " << s1 << ", s2: " << s2 << endl;
    cout << "You can assign a C style string to a string object.\n";
    cout << "s2 = \"buzzard\"\n";
    s2 = "buzzard";
    cout << "s2: " << s2 << endl;
    cout << "String objects can be combined: s3 = s1 + s2\n";
    s3 = s1 + s2;
    cout << "s3: " << s3 << endl;
    cout << "You can add string objects.\n";
    s1 += s2;
    cout << "s1 += s2 --> s1 = " << s1 << endl;
    s2 += " for a day";
    cout << "s2 += \" for a day\" --> s2 = " << s2 << endl;

    return 0;
}

// You can substitute a string object for a string object: s2 = s1
// s1: penguin, s2: penguin
// You can assign a C style string to a string object.
// s2 = "buzzard"
// s2: buzzard
// String objects can be combined: s3 = s1 + s2
// s3: penguinbuzzard
// You can add string objects.
// s1 += s2 --> s1 = penguinbuzzard
// s2 += " for a day" --> s2 = buzzard for a day

여기서 이스케이프 시퀀스 \"는 문자열의 경계를 표시하는 것이 아니라 글자로서의 큰따옴표를 나타낸다.

 

 

string 클래스 조작

// strtype3.cpp -- string 클래스의 기타 기능
#include <iostream>
#include <string>
#include <cstring>      // C 스타일 문자열 라이브러리

int main()
{
    using namespace std;
    char charr1[20];
    char charr2[20] = "jaguar";
    string str1;
    string str2 = "panther";

    // string 객체의 대입과 문자 배열의 대입
    str1 = str2;        // str2를 str1에 복사
    strcpy(charr1, charr2);  // charr2를 charr1에 복사

    // string 객체와 추가와 문자 배열의 추가
    str1 += " paste";       // str1의 끝에 paste를 추가
    strcat(charr1, " juice");       // charr1의 끝에 juice를 추가

    // string 객체의 길이 구하기와 C스타일 문자열의 길이 구하기
    int len1 = str1.size();     // str1의 길이를 구한다.
    int len2 = strlen(charr1);  // charr1의 길이를 구한다.

    cout << str1 << " string has "
        << len1 << " characters.\n";
    cout << charr1 << " has "
        << len2 << " characters.\n";
    return 0;
}

// panther paste string has 13 characters.
// jaguar juice has 12 characters.

 

 

한번에 한단어가 아닌 한 행을 읽는 방법에 대한 코드

// strtype4.cpp -- 행단위 입력
#include <iostream>
#include <string>
#include <cstring>
int main()
{
    using namespace std;
    char charr[20];
    string str;

    cout << "The length of the string in 'charr' before input: "
        << strlen(charr) << endl;
    cout << "The length of the string in 'str' before input: "
        << str.size() << endl;
    cout << "Enter a line of text: \n";
    cin.getline(charr, 20);      // 최대 길이를 나타낸다.
    cout << "Entered Text: " << charr << endl;

    cout << "Enter another line of text:\n";
    getline(cin, str);      // 이제 cin은 길이 지정자가 아니라 매개변수
    cout << "Entered Text: " << str << endl;
    cout << "The length of the string in 'charr' after typing: "
        << strlen(charr) << endl;
    cout << "The length of the string in 'str' after typing: "
        << str.size() << endl;
    return 0;
}

// The length of the string in 'charr' before input: 3
// The length of the string in 'str' before input: 0
// Enter a line of text:
// peanut butter
// Entered Text: peanut butter
// Enter another line of text:
// blueberry jam
// Entered Text: blueberry jam
// The length of the string in 'charr' after typing: 13
// The length of the string in 'str' after typing: 13

charr는 초기화되지 않은 배열이니 정의되지 않는다. 널 값을 만날때까지 바이트들을 카운트하기때문에 사람마다 다른 값이 나올 것이다. (랜덤한 위치에서 널문자를 만나기 때문에)

 

반면 초기화되지 않은 string은 자동으로 크기가 0으로 설정된다.

728x90