본문 바로가기
Coding Test/C++ 줍줍

[C++ 줍줍] string의 특정 값 제거하기 : index, 문자 기준

by seoyamin 2022. 7. 5.

▷ 문제 상황 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;
 }