공부/C++
4. C++ Vector 공백 제거
하나리나
2021. 8. 19. 20:39
반응형
다음과 같은 vector vct가 있을 때,
vct = {"112","082 17", "1544 2311"}
vct의 첫 번째 원소는 공백이 없지만, vct의 두 번째, 세 번째 원소에는 공백이 있습니다.
erase를 이용하여 이 원소를 제거할 수 있습니다.
1. vector 생성 및 초기화
vector <string> vct = {"112", "082 17", "1544 2311"};
2. string을 임시로 저장하는 변수 선언
string tmp;
3. for 구문을 돌면서 vct 원소에 공백이 있을 경우 공백 제거
for (int i = 0; i < 3; i++) {
tmp = vct[i];
tmp.erase(remove_if(tmp.begin(), tmp.end(), isspace), tmp.end());
cout << tmp << endl; // 공백이 제대로 제거 되었는지 확인
}
4. 전체 코드
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main() {
vector <string> vct = { "112","082 17","1544 2311" };
string tmp;
//vct.erase(remove_if(vct.begin(), vct.end(), isspace), vct.end());
for (int i = 0; i < 3; i++) {
tmp = vct[i];
tmp.erase(remove_if(tmp.begin(), tmp.end(), isspace), tmp.end());
cout << tmp << endl;
}
return 0;
}
반응형