물먹는산세베리아

[C++] String class 함수 본문

Language/C, C++

[C++] String class 함수

suntall 2020. 4. 13. 05:24

< C++ string class 함수 정리 >

 

[사용 예시]

<string>

string str1 = “IamHungry”;

str1.at();

 

1. at()

Index에 숫자(n)가 들어가며, n에 해당하는 문자를 반환한다.

Index가 string의 범위를 벗어나면 예외를 뱉는다.

 

2. [n]

Index에 숫자(n)가 들어가며, n에 해당하는 문자를 반환한다.

Index 범위를 검사하지 않아 at 함수보다 빠르지만 예외를 뱉지 않는다.

 

3. front()

string의 맨 앞 인자를 반환한다.

 

4. back()

string의 맨 뒤 인자를 반환한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string str1 = "Iamhungry";
    string str2 = "Metoo";
 
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    cout << endl;
 
    //at
    cout << "1. at()" << endl;
    cout << "str1.at(3): " << str1.at(3<< endl;
    cout << endl;
 
    cout << "2. '[]'" << endl;
    cout << "str1[3]: " << str1[3<< endl;
    //cout << "str1[12]: " << str1[12] << endl; //Debug Assertion Failed
    cout << endl;
 
    cout << "3. front()" << endl;
    cout << "str1.front(): " << str1.front() << endl;
    cout << endl;
 
    cout << "4. back()" << endl;
    cout << "str1.back(): " << str1.back() << endl;
    cout << endl;
 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

 

 

5. size()

string의 사이즈를 반환한다.

 

6. length()

string의 길이를 반환한다.

Size 함수의 결과값과 같다.

 

7. capacity

string 객체에 할당된 메모리 크기를 반환한다.

string 길이가 증가할 수 있기 때문에 size에 비해 여유롭게 메모리 할당을 한다.

 

8. resize(n)

string을 n만큼의 크기로 바꾼다.

원래 사이즈 보다 작으면 남은 string을 버리고, 크다면 빈 공간으로 남은 공간을 채운다.

Resize(n, c)의 경우 남은 공간을 c로 채운다.

 

9. reserve(n)

메모리를 추가로 할당할 때마다 capacity가 그에 맞게 계속 늘어나는 것을 방지하기 위해 미리 예고하는 것.

“n 크기의 string이 들어올 테니 맞는 capacity를 할당해라”

 

10. clear()

문자열 값을 지우는 함수이다.

크기와 길이는 0이 되지만 capacity는 그대로이다.

 

11. empty()

String이 비었는지 확인하는 함수이다.

비었음(size, length ==0)이면 true를 반환한다.

Capacity와는 관계 없다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string str1 = "Iamhungry";
    string str2 = "Metoo";
    string str3 = "hungry";
 
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    cout << "str3: " << str3 << endl;
    cout << endl;
 
    //size()
    cout << "5. size()" << endl;
    cout << "str1.size(): " << str1.size()<< endl;
    cout << endl;
 
    //length()
    cout << "6. length()" << endl;
    cout << "str1.length(): " << str1.length() << endl;
    cout << endl;
 
    //capacity()
    cout << "7. capacity()" << endl;
    cout << "str1.capacity(): " << str1.capacity() << endl;
    cout << endl;
 
    //resize()
    cout << "8. resize(n)" << endl;
    str1.resize(3);// 원래 사이즈보다 작으므로 남은 string을 버린다.
    cout << "str1.resize(3)-> "<< endl;// Iam만 살아남는다
    cout << "str1: " << str1 << endl;
    cout << "str1.size(): " << str1.size() << endl;
    cout << "str1.length(): " << str1.length() << endl;
    cout << "str1.capacity(): " << str1.capacity() << endl;
    cout << endl;
 
    //reserve()
    cout << "9. reserve(n)" << endl;
    str1.reserve(1);
    cout << "str1.reserve(1)-> " << endl;
    cout << "str1: " << str1 << endl//Iam그대로 있고, 곧 1만큼의 string이 들어올테니 그에 맞는 capacity를 할당하라
    cout << "str1.size(): " << str1.size() << endl;
    cout << "str1.length(): " << str1.length() << endl;
    cout << "str1.capacity(): " << str1.capacity() << endl;
    cout << endl;
    
    str1 += str3; //str1 = Ianhungry로 바꿔주기
 
    //clear()
    cout << "10. clear()" << endl;
    cout << "str1: " << str1 << endl
    cout << "str1.size(): " << str1.size() << endl;
    cout << "str1.length(): " << str1.length() << endl;
    cout << "str1.capacity(): " << str1.capacity() << endl//메모리는 변동 없음.
    cout << endl;
 
    //empty
    cout << "11. empty()" << endl;
    cout << "str1.empty(): " << str1.empty() << endl;
    // clear로 인해 문자열이 지워짐 따라서 string이 비어있으므로 1(true) 출력
    cout << endl;
 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

 

 

12. c_str()

C++ 형태의 문자열을 C 형태로 변경한다.

“IamHungry” -> “IamHungry\0”

 

13. substr()

index에서부터 len만큼 잘라서 반환한다.

Substr(3) : 3번째 인자부터 끝까지의 문자열을 반환 //0부터 세어야 한다.

Substr(3,1) : 3번째 인자부터 1의 길이만큼 문자열을 반환

 

14. replace()

Index 위치에서 len 길이까지의 범위를 문자열 전체로 대체한다.

str1.Replace(3, 2, str2) str1의 3번째 인자에서부터 2개를 str2로 대체

 

15. compare()

호출한 string 값과 매개변수로 들어온 문자열을 비교하여 같으면 0을 반환한다.

매개변수보다 작으면(사전순 빠르면) -1을 반환하고

매개변수보다 크면(사전순 느리면) 1을 반환한다.

앞글자부터 비교하여 달라지는 문자를 기준으로 반환한다.

Str1.compare(0, 3, str2, 5, 3): str1의 0번째 인덱스부터 길이 3인 문자열과 str2 문자열의 5번째 인덱스부터 길이가 3인 분자열을 비교한다.

 

16. copy()

복사를 하는 함수이다.

copy(호출한 문자열을 첫번째 매개변수 문자열에 복사, 복사할 문자열의 길이, 복사 시작할 위치)

copy(arr,4,6): 6번째 index부터 4의 길이만큼 복사

 

17. find()

호출한 문자열과 매개변수로 들어온 문자열 중에 일치하는 게 있는지 확인하는 함수이다.

일치하는 게 있다면 일치하는 부분의 첫번째 index를 반환한다.

str1.find(“Iam”): “IamHungry” -> 처음부터 일치하므로 0을 반환

str1.find(“Iam”,3): 3번째 인자부터 Iam을 찾는 것

 

18. push_back(c)

함수를 호출하는 스트링의 맨 뒤에 문자 c를 더하는 함수이다. (문자 1개)

str1.push_back(‘a’): “IamHungrya”

 

19. pop_back()

호출한 string의 맨뒤에 있는 문자 하나는 없애는 함수이다.

str1.pop_back(): “IamHungryabc” -> “IamHungrayab”

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string str1 = "Iamhungry";
    string str2 = "Metoo";
    string str3 = "hungry";
    string str4 = "Iamnothungry";
 
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    cout << "str3: " << str3 << endl;
    cout << "str4: " << str4 << endl;
    cout << endl;
 
    //c_star()
    cout << "12. c_str()" << endl;
    cout << "str3.c_str(): " << str3.c_str() << endl//뒤에 \0(NUL) 생김
    cout << endl;
 
    //substr()
    cout << "13. substr(n)" << endl;
    cout << "str1.substr(3): " << str1.substr(3<< endl//3번째 문자부터 끝까지
    cout << "str1.substr(3,2): " << str1.substr(3,2<< endl//3번째 문자부터 2의 길이만큼
    cout << endl;
 
    //replace()
    cout << "14. replace(n1, n2, str)" << endl;
    cout << "str3.replace(3, 2 ,str1): " << str3.replace(32, str1) << endl;
    //hungry 의 gr를 Iamhungry로 대체
    cout << endl;
 
    //compare()
    cout << "15. compare()" << endl;
    cout << "str1.compare(str4): " << str1.compare(str4) << endl;//Iam이 같으므로 str1의 h와 str4의을 비교, h가 더 작으므로 -1 출력
    cout << "str1.compare(\"Iamhappy\"): " << str1.compare("Iamhappy"<< endl// h > a
    cout << "str1.compare(1, 3, str4): " << str1.compare(13, str4) << endl//amh과 Iamnothungry을 비교, 대문자<소문자(아스키코드)
    cout << "str1.compare(3, 4, str4 ,6, 4)" << str1.compare(34, str4, 64<< endl;//hung와 hung 비교
    cout << endl;
    
    cout << "<현재>" << endl;
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    cout << "str3: " << str3 << endl;
    cout << "str4: " << str4 << endl;
    cout << endl;
 
    //copy()
    cout << "16. copy()" << endl;
    char arr1[100];
    cout << "str1.copy(arr1, 6, 3)-> " << endl;
    int arrLen = str1.copy(arr1, 63);
    cout << "arrLen: " << arrLen << endl;
    arr1[arrLen] = '\0';
    cout << "arr1: " << arr1 << endl;
    cout << endl;
 
    //find()
    cout << "17.find()" << endl;
    cout << "str1.find(\"am\"): " << str1.find("am"<< endl//첫번째 index에서 일치
    cout << "str1.find(\"am\",2): " << str1.find("am",2<< endl// error
    cout << endl;
 
    //push_back()
    cout << "18.push_back()" << endl;
    str2.push_back('a'); // Metoo + a
    cout << "str2.push_back('a'): " << str2 << endl//변수만 출력
    cout << endl;
 
    //pop_back()
    cout << "19.pop_back()" << endl;
    str2.pop_back();
    cout << "str2.pop_back(): " << str2 << endl//변수만 출력
 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

 

 

20-1. begin()

문자열의 첫 번째 문자를 가리키는 반복자(iterator 포인터)를 반환한다.

20-2. end()**

문자열의 마지막의 바로 다음을 가리키는 반복자(iterator 포인터)를 반환한다.

 

21. swap(str1, str2)

복사를 하는 것이 아니라 참조를 교환하여 str1과 str2를 바꾸는 함수이다.

 

22. operator+

string끼리 이어 붙이는 함수이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string str1 = "Iamhungry";
    string str2 = "Metoo";
    string str3 = "hungry";
    string str4 = "Iamnothungry";
 
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    cout << "str3: " << str3 << endl;
    cout << "str4: " << str4 << endl;
    cout << endl;
 
    //begin()
    cout << "20. begin(), end()" << endl;
    string::iterator iter = str1.begin();
    for (; iter != str1.end(); ++iter)
    {
        cout << *iter << " ";//"I "를 출력
    }
    cout << endl << endl;
 
    //swap()
    cout << "21. swap()" << endl;
    cout << "swap(str1, str2) ->" << endl;
    swap(str1, str2);
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    cout << endl;
 
    //'+'
    cout << "22. +" << endl;
    cout << "str3 + str4: " << str3 + str4 << endl;
    cout << endl;
 
 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

 



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

SW에듀서포터즈 C언어_포인터활용 교육자료  (0) 2021.07.26
SW에듀서포터즈 C언어_포인터 교육자료  (0) 2021.07.23
[C++] 포인터  (0) 2020.05.26
[C++]C-스트링 함수  (0) 2020.04.13