본문 바로가기

Language/C++

[C++] <string> 라이브러리

728x90
반응형

C++에서 문자열을 다룰 수 있는 두 가지 방법

- C-string

C언어에서 사용해오던 문자열로, '/0'으로 끝나는 char 타입의 배열을 취급하는 방법이다.

char s[100]; 
scanf("%s", s);

- string 클래스

C++ 표준 라이브러리에서 제공하는 클래스로 문자열의 끝에 '/0' 문자가 들어가지 않으며, 문자열의 크기를 동적으로 변경 가능하다.

string str = "";

getline(cin, str);
cout << str;

str.append("you");
cout << str;
cout << str[0];

 

string 클래스의 입/출력

C++ 입출력 방식인 cin, cout으로 입출력이 가능하며, getline 함수도 이용할 수 있다. (scanf, printf 사용 불가)

string str;             // 문자열 생성

cin >> str;             // 스페이스가 들어간 문자열의 경우 첫 번째 것만 입력받으므로 주의!!
cout << str; 

getline(cin, str);      // '\n' 이전까지의 문자열, 즉 한 줄을 통째로 입력받는다. (공백 포함)
cout << str;

getline(cin, str, 'a'); // 'a' 문자 이전까지의 문자열을 입력받는다.  getline(cin, str, '\n') == getline(cin, str)
cout << str;

 

** getline() 함수를 사용할 때 주의할 점

int n;
string str;
cin >> n;
getline(cin, str);

위 코드대로 실행을 하면 n을 입력 받은 후 문자열을 입력받지 않고 바로 다음 코드로 넘어가게 된다. 버퍼에 정수 값을 입력한 뒤 누른 엔터(‘\n’)가 그대로 남아있어 getline()에 들어가기 때문이다.

 

이를 해결하기 위해 cin.ignore() 라는 함수를 사용할 수 있다.

int n;
string str;
cin >> n;
cin.ignore();
getline(cin, str);

cin.ingore()가 입력 버퍼의 모든 내용을 제거해주어 getline()이 정상적으로 동작할 수 있다.

 

 

string 클래스 생성

먼저 헤더 파일을 추가해주어야 한다.   #include <string>

string을 생성하는 방법은 다음과 같다.

// 빈 문자열을 가지도록 생성
string str;

// 생성자에 초기값을 넘겨주는 방식
string str = "abcde";
string str("abcde");

// c 스트링과의 호환
char s[] = {'a', 'b', 'c', 'd', 'e'};
string str(s);

// 문자열 내용을 복사한 새로운 객체 생성 방식
string str = "abcde";
string str2(str);   // string 객체의 문자열 내용 복사하여 새로운 객체 생성(주소복사X)

// new, delete를 이용한 동적할당 방식1
string *p = new string();   // new를 이용하여 객체를 생성하려면 포인터 변수로 선언해야 한다.
p->append("Great!");        // 포인터 변수 p가 가리키고 있는 객체의 함수 append 사용
cout << *p << endl;         // 포인터 변수가 가리키고 있는 객체의 값을 가져오려면 '*'를 붙여줘야 한다.
delete p;                   // 메모리 반환

// new, delete를 이용한 동적할당 방식2
string *p = new string("C++");  // 위의 방식에서 여기만 다름
p->append("Great!");
cout << *p << endl;
delete p;

// new, delete를 이용한 동적할당 방식3
string str = "abcd"
string *p = new string(str);   // 위의 방식에서 여기만 다름
p->append("Great!");
cout << *p << endl;
delete p;

 

string 클래스 객체끼리의 비교연산

'==' 연산자 - 문자열이 같은지 비교

string str1 = "abcde";
string str2 = "abcde";
string str3 = "abcff";

cout << (str1 == str2) << " " << (str1 == str3) << endl;   // true(0) false(1) 출력

'>' 또는 '<' 연산자 - 사전순서 비교

맨 앞의 문자가 아니라 전체 문자를 비교해본 결과가 나옴

string str1 = "abcde";
string str2 = "ccccc";

cout << (str1 < str2) << " " << (str1 > str2) << endl;   // true(1) false(0) 출력

 

string 클래스의 자주 사용되는 메소드

length() - 문자열 길이 반환

size() - 문자열 길이 반환

capacity() - 사용중인 메모리 크기 반환

string str = "012345";

cout << str.length() << endl;    // 6
cout << str.size() << endl;      // 6
cout << str.capacity() << endl;  // 22 (가변)

append() 또는 '+' - 문자열 연결

append()의 경우 인자로 'c' 같이 char 형을 사용할 수 없다. "c"는 가능하다.

char형을 더해주고 싶은 경우 + 연산을 이용하자.

string str = "aaa"

str.append("bbb");
cout << str << endl;    // "aaabbb"

insert() - 문자열 삽입

string str = "012345";

str.insert(2, "bbb");    // index가 2인 위치에 있는 문자 앞에 삽입함.
cout << str << endl;     // "01bbb2345"

replace() - 문자열 대체

string str = "012345";

str.replace(2, 3, "bbb");    // index가 2인 위치에 있는 문자부터 ~ 3개의 문자를 "bbb"로 대체함
cout << str << endl;         // "01bbb5"

erase() - 부분 지우기

string str = "012345";

str.erase(1, 4);       // index 1부터 4개의 문자를 지움
cout << str << endl;   // "05"

clear() - 전체 지우기

string str = "012345";

str.clear();          // 저장되어 있는 문자열을 모두 지움
cout << str << endl;  // ""

substr() - 부분 문자 반환받기

string str = "012345";

cout << str.substr(2) << endl;     // "2345" index 2의 위치부터 끝까지의 문자 반환
cout << str.substr(2, 3) << endl;  // "234"  index 2의 위치부터 3개의 문자 반환

find()

- 문자가 존재하는 경우, 해당 위치의 index 반환받기

- 문자열이 존재하는 경우, 문자열이 시작되는 index 반환받기

- 존재하지 않으면 -1을 반환받음

string str = "kkk abc aaa";
 
cout << str.find("f"); << endl;       // -1
cout << str.find("aac"); << endl;     // -1
cout << str.find("aaa"); << endl;     // 8
cout << str.find("kkk", 4); << endl;  // -1  인덱스 4의 위치부터 "kkk"를 찾는데 존재하지 않음

[] 또는 at() - 해당 인덱스의 문자 한 개를 char 형으로 반환함

string str = "012345";

cout << str[1] << endl;     // 1
cout << str.at(1) << endl;  // 1

stoi() - string -> int 변환 수행  (인자는 반드시 string 형을 넘겨주어야 함. str[0]은 char형이므로 불가)

to_string() - int -> string 변환 수행

// string의 문자열 전체를 숫자로 변환하는 경우
string str = "2000";
int a = stoi(str);

// string의 문자 한 개를 숫자로 변환하는 경우
string str = "2000";
string temp = str[0];   // index를 포함한 값인 경우 여기처럼 선언과 할당을 분리시켜줘야 한다.
int b = stoi(temp);

int a = 12;
string str = to_string(a);

toupper() - 소문자를 대문자로 변환 (char형만 가능)

tolower() - 대문자를 소문자로 변환 (char형만 가능)

string str = "abcde";
str[2] = toupper(str[2]);
cout << str;       // "abCde"

string str = "abcde";
str[2] = tolower(str[2]);
cout << str;       // "ABcDE"

isdigit() - 문자가 숫자인지 아닌지 판별해줌

isalpha() - 문자가 영어인지 아닌지 판별해줌

string str = "1ABCDE";

cout << isdigit(str[0]) << endl;   // 1 (true)
cout << isdigit(str[2]) << endl;   // 0 (false)

cout << isalpha(str[0]) << endl;    // 0 (false)
cout << isalpha(str[2]) << endl;    // 1 (true)

empty() - 문자열이 비어있나 판별해줌

string str1 = "";
cout << str1.empty() << endl;    // 1(true)

string str2 = "abcde";
cout << str2.empty() << endl;    // 0(false)

swap() - 스트링 문자열을 서로 교환함

string str1 = "aaa";
string str2 = "ccc";

str1.swap(str2);

cout << str1 << endl;    // "ccc"
cout << str2 << endl;    // "aaa"

pop_back() - 맨 뒤의 문자를 pop

push_back() - 맨 뒤에 push 함

string str = "abc";

str.pop_back();
cout << str << endl;      // "ab"

str.push_back('c');
cout << str << endl;      // "abc"

front() - 맨 앞의 문자 반환

back() - 맨 뒤의 문자 반환

string str = "abc";

cout << str.front() << endl;   // "a"
cout << str.back() << endl;    // "e"
728x90
반응형

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

[C++] OOP - 클래스(class)  (0) 2021.10.24
[C++] <random> 라이브러리 (난수 생성)  (0) 2021.10.03
[C++] OOP - 생성자와 소멸자  (0) 2021.07.09
[C++] 공용체, 열거체  (0) 2021.07.03
[C++] 구조체  (0) 2021.07.03