티스토리 뷰

this 포인터

- 객체 자기 자신을 가르키는 포인터

 

string 클래스를 이용한 문자열

- c++ string 클래스의 객체

- <string> 헤더파일을 import 한다.

- 다양한 문자열 연산을 다루는 연산자와 멤버 함수를 가지고 있다.

- 문자열, 스트링, 문자열 객체, string 객체 등 혼용한다.

 

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
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
#include<iostream>
#include<string>
 
using namespace std;
int main() {
    //string 클래스 예제 p.188
    //1.문자열 비교 compare()
    string name = "Dong";
    string alias = "hongGil";
 
    int res = name.compare(alias);
    if (res == 0)
        cout << "두 문자열이 같다." << endl;
    else if (res < 0)
        cout << name << " < " << alias << endl;
    else
        cout << alias << " < " << name << endl;
 
    //p.190 
    //2.문자열 삽입(insert)
    string a("I love C++");//삽입 전 문자열
    cout << a << endl;
 
    a.insert(2,"really ");//삽입 후 문자열
    cout << a << endl;
 
 
    //3.문자열 일부분을 추출함수 substr()
    string b = "I love C++";
    cout << b << endl;
 
    string c = b.substr(2,4); // substr(시작 인덱스, 추출할 문자열 길이)
    cout << c << endl;
 
    string d = b.substr(2); // 시작위치만 지정하면 시작위치부터 문자열 끝까지 추출한다.
    cout << d << endl;
 
    //4.문자열 검색 find()
    string e = "I love love C++";
 
    int index = e.find("love");//특정 문자열이 있는 index를 반환.
    cout << index << endl;
 
    index = e.find("v");//특정 문자열이 있는 index를 반환.
    cout << "v문자열의 위치는 " << index << endl;
 
    index = e.find("v"5);//시작위치를 지정하면 그 이후의 v문자열을 찾는다.
    cout << "2번째 v문자열의 위치는 " << index << endl<<endl;
 
    cout << "20+20의 합을 출력" << endl;
    //+ 기호의 위치가 몇번째 있는지 index 번호 출력.
    
    string s = "20+20";
    index = s.find("+");
    cout << "+기호의 위치는 " << index << endl;
 
    
    int num1,num2, sum = 0, startIndex = 0;
    string s1 = s.substr(startIndex, index);
    num1 = atoi(s1.c_str());
 
    string s2 = s.substr(index);
    num2 = atoi(s1.c_str());
 
    sum = num1 + num2;
    
    cout << "계산한 합은 "<< sum << endl;
 
    return 0;
}
cs

 

<실행 결과>

 

<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
#include<iostream>
#include<string>
 
using namespace std;
 
int main() {
    string s, s1;
    int startIndex = 0, index, num, sum = 0;
 
    cout << "수식입력";
    getline(cin, s, '\n');
    
    while (true) {
        index = s.find('+', startIndex);
        s1 = s.substr(startIndex, index);
        num = atoi(s1.c_str());
        sum += num;
        startIndex = index + 1;
        if (index == -1)
            break;
    }
    cout << "result = " << sum <<endl;
 
    return 0;
}
cs

 

<실행 결과>

 

댓글