Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 깊이 우선 탐색
- 코드블럭 테마
- ML-Agents
- Mathf.Clamp
- unity
- LayerMask
- git-lfs
- Quaternion.Euler
- 유니티 Collision
- LFS
- c++ 문자열 자르기
- 유니티 ResourceManager
- 유니티
- 유니티 Rotate
- c++
- 유니티 오브젝트 풀링
- 이진트리
- 유니티 InputManager
- 유니티 Vector3
- 너비 우선 탐색
- 오브젝트 풀링
- Raycast
- eulerAngles
- 유니티 시야 가림
- LookRotation
- 유니티 리소스매니저
- 알고스팟
- InputManager
- 유니티 머신러닝
- 소스코드 줄번호
Archives
- Today
- Total
무민은귀여워
문자열 자르기 substr / istringstream / stringstream / strtok 본문
반응형
문자열이 주어졌을 때, 공백 단위로 단어를 나누는 방법
ex) 문자열 "apeach frodo muzi" 을 "apeach", "frodo", "muzi" 로 나누어 저장
단어 갯수를 알 경우
단어 갯수를 모를 경우
1. substr
#include <iostream> #include <vector> using namespace std; int main() { string str = "apeach frodo muzi"; vector<string> names; for (int i = 0; i < 3; i++) { names.push_back(str.substr(0, str.find(" "))); str = str.substr(str.find(" ") + 1); } for (auto name : names) { cout << name << endl; } return 0; }
2. istringstream
#include <iostream> #include <vector> #include <sstream> using namespace std; int main() { string str = "apeach frodo muzi"; vector<string> names; istringstream iss(str); for (int i = 0; i < 3; i++) { string tmp; iss >> tmp; names.push_back(tmp); } for (auto name : names) { cout << name << endl; } return 0; }
3. stringstream
#include <iostream> #include <vector> #include <sstream> using namespace std; int main() { string str = "apeach frodo muzi"; vector<string> names; stringstream ss(str); string token; while (ss >> token) { names.push_back(token); } for (auto name : names) { cout << name << endl; } return 0; }
4. strtok
#include <iostream> #include <vector> using namespace std; int main() { string str = "apeach frodo muzi"; vector<string> names; vector<char> w(str.begin(), str.end()); w.push_back('\0'); char* ch = &w[0]; char* context = NULL; char* tok = strtok_s(ch, " ", &context); while (tok != nullptr) { names.push_back(string(tok)); tok = strtok_s(nullptr, " ", &context); } for (auto name : names) { cout << name << endl; } return 0; }

반응형
'IT > c, c++' 카테고리의 다른 글
스마트 포인터 ( unique_ptr, shared_ptr, weak_ptr ) (1) | 2021.05.18 |
---|---|
csv 파일 읽고 쓰기 (0) | 2021.05.18 |
같은 자료형인 두 값을 교환하는 함수 형식 매크로 ( swap 매크로 ) (0) | 2021.05.18 |
typedef 보다 별칭 선언을 선호하라 (0) | 2020.01.17 |
[c++] map 사용 예제 (0) | 2019.11.28 |