▷ 문제 상황 1
string의 특정 인덱스 값을 제거하고 싶다!
▶ 해결 방법
erase( ) 메소드를 이용
ex )
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "HAPPY"
// 첫 문자 삭제
s.erase(s.begin());
// 마지막 문자 삭제
s.erase(s.end());
// 'index = n'인 문자 삭제
s.erase(s.begin() + n);
// 'index = a'부터 'index = b'까지 삭제
s.erase(s.begin() + a, s.begin() + b);
// 'index = n'부터 k개 문자 삭제
s.erase(n, k);
// 'index = n'부터 끝까지 전부 삭제
s.erase(n);
return 0;
}
▷ 문제 상황 2
string의 특정 문자 값을 제거하고 싶다!
▶ 해결 방법 1
remove( ), erase( ) 메소드를 이용
remove( ) : 타겟 문자가 위치하는 모든 인덱스를 erase( )에게 return 한다.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "HAPPY BIRTHDAY"
// 문자 A 제거
s.erase(remove(s.begin(), s.end(), 'A'), s.end());
// 공백 제거
s.erase(remove(s.begin(), s.end(), ' '), s.end());
return 0;
}
▶ 해결 방법 2
regex_replace( ) 메소드를 이용
#include <regex>
regex_replace(타겟인 before 문자열, regex( ), 바꾸려는 after 문자열)
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main() {
string s = "HAPPY BIRTHDAY"
// 문자 A를 삭제하기
s = regex_replace(s, regex("A"), "");
// 문자 A를 a로 바꾸기
s = regex_replace(s, regex("A"), "a");
return 0;
}
'Coding Test > C++ 줍줍' 카테고리의 다른 글
[알튜비튜 줍줍] sort 함수 정리 (0) | 2022.09.03 |
---|---|
[C++ 줍줍] 벡터를 이용한 집합 계산 : 합집합, 교집합, 차집합 (0) | 2022.07.25 |
[C++ 줍줍] Map의 value에 여러 개의 값을 저장하기 (0) | 2022.07.05 |
[c++ 줍줍] vector 정리 (0) | 2022.06.14 |
[c++ 줍줍] 대문자 <=> 소문자 (0) | 2022.05.30 |