헤더 라이브러리
#include <string> 사용
1. getline() → 공백을 포함하여 한 줄을 전부 읽어옴
getline(입력스트림, 객체)
cin.getline()과 달리 인수로 char* 포인터 형식을 넣어줘선 안된다
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
string age;
getline(cin, name); // 문자열 이름 입력 받기
getline(cin, age); // 문자열 나이 입력 받기
}
- 파일을 스트림에 연결하고 싶을 때 ⇒ open 멤버함수 사용하기
#include <iostream>
#include <fstream> // 파일 입출력 헤더 라이브러리
#include <string>
using namespace std;
int main() {
////콘솔에서 입력받기
//string test1;
//getline(cin, test1);
//파일 연결하기 - open 멤버함수
ifstream fin;
fin.open("input.txt");
ofstream fout;
fout.open("output.txt");
}
2. substr(int pos, int count) → 원래 문자열에서 [pos, pos+count] 범위의 부분 문자열을 리턴
- pos : 첫번째 문자 위치
- count : 부분 문자열의 위치
- default 값은 npos :: 자동으로 pos부터 문자열의 끝까지 리턴 ⇒ 전체 리턴
#include <iostream>
#include <string>
using namespace std;
int main() {
string a("Hi, my name is cello");
string new1 = a.substr(10);//a 문자열의 인덱스 10~ 끝까지
cout << new1 << endl;
string new2 = a.substr(5, 3); // index 5~8(5+3) return
cout << new2 << endl;
}
3. find()
#include <iostream>
#include <string>
using namespace std;
int main() {
string a("Hi, my name is cello");
int n = a.find("is"); // "is"의 시작 위치 return
cout << n << endl;
int g = a.find("is",5); // "is"의 시작 위치를 5번째 인덱스부터 찾아서 return
cout << g << endl;
}
4. stoi(string to int), stol(string to long), stoll(long long) :: 문자열을 정수로 변환
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "234234";
int result = stoi(str1);
cout << result;
}
- to_string :: 정수, 실수 → 문자열로
#include <iostream>
#include <string>
using namespace std;
int main() {
int num = 1232353;
string str = to_string(num); // "1232353"
cout << str;
}
5. front(), back()
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Happy new year!!~";
cout << s.front() << endl; // 맨 앞글자 H 출력
cout << s.back() << endl; // 맨 뒷글자 ~ 출력
}
6. + 연산자
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "NEW";
string s2 = "YEAR";
cout << s1 + s2 << endl;
}
7. append(num, char a)
string str = "Neww";
str.append(2, '9'); // "Neww99"
8. push_back() : 뒤에 문자 1개만 추가함 → vector와 같이 사용
str.push_back("w"); // just one word
9. insert :: 문자열 중간에 삽입
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "i reading";
str.insert(2, "love ");
cout << str << endl; // "i love reading"
}
10. swap :: 서로 string 문자열 값을 교환
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "i reading";
string str1 = "new";
str.swap(str1);
cout << str << endl; // new
cout << str1; // i reading
}
11. max_size() :: 최대한 메모리를 할당했을 경우, 저장할 수 있는 문자열의 길이를 반환
'코딩 > C++' 카테고리의 다른 글
백준 문제풀이 C++ [220119] - 문자열 (0) | 2022.01.19 |
---|---|
백준 문제풀이 C++ [220116] - 문자열 (0) | 2022.01.16 |
백준 문제풀이 C++ [220112] - 함수, 문자열 (0) | 2022.01.13 |
[C++] :: STL <vector> iterator(반복자) (0) | 2022.01.12 |
백준 문제풀이 C++ 배열 [220111] - 1차원 배열 (0) | 2022.01.12 |