[C++] string::erase - 특정 문자열 삭제 함수

반응형
반응형

[C++] string::erase

*개인적인 공부 내용을 기록하는 용도로 작성한 글 이기에 잘못된 내용을 포함하고 있을 수 있습니다.

 

_contents

#1 string::erase

#2 example

#2.1 sequnce _ 특정 길이 만큼의 문자열 제거

#2.2 ch _ 특정 위치의 문자 제거

#2.3 range _ 특정 범위를 지정해 문자열 제거

#2.4 erase & find _ 특정 문자를 탐색하여 제거


#1 string::erase

<string>헤더에 정의된 erase함수는 문자열에서 특정한 문자열을 제거해주는 기능을 수행하는 함수이다.

erase 함수의 사용법은 3가지로 나뉜다.

string& erase(size_t pos = 0, size_t len = npos); // pos부터 len 길이만큼 문자열을 제거한다.
iterator erase(const_iterator p); // p에 해당하는 문자를 제거한다.
iterator erase(const_iterator first, const_iterator last); // (first, last] 길이의 문자열을 제거한다.

#2 example

#2.1 sequnce _ 특정 길이 만큼의 문자열 제거

첫 번째 파라미터제거할 문자열의 시작 위치를, 두 번째 파라미터제거할 문자열의 길이를 넣어 주어 삭제를 수행한다.

다음은 "This is test sentence" 문자열에서 "This "를 삭제하는 코드이다.

#include <algorithm>
#include <string>
#include <iostream>
using namespace std;

int main(){
	string str = "This is test sentence";
	// string& erase(size_t pos = 0, size_t len = npos);
	// pos부터 len길이 만큼의 문자를 제거한다.
	// ... delete "This "
	str.erase(0, 5);
	cout << str << endl;

	return 0;
}
[실행결과] test sentence

 

#2.2 ch _ 특정 위치의 문자열 제거

iterator를 이용해 특정 위치의 문자를 제거한다.

문자열이름.erase(문자열이름.begin() + (제거할 위치 - 1)) 형식으로 특정 문자를 삭제할 수 있다.

다음은 "This is test sentence" 문자열에서 세 번째 위치에 존재하는 "i" 문자를 삭제하는 예제이다.

#include <algorithm>
#include <string>
#include <iostream>
using namespace std;

int main(){
	string str = "This is test sentence";
	// iterator erase(const_iterator p);
	// p에 위치하는 문자를 제거한다.	
	// ... delete "i"
	str.erase(str.begin() + 2);
	cout << str << endl;
	return 0;
}
[실행결과] Ths is test sentence

 

#2.3 range _ 특정 범위를 지정해 문자열 제거

erase 함수에 두 개의 파라미터 (first, last) 를 보내어 지정 범위의 문자열을 제거할 수 있다.

(first, last] 범위의 문자열을 삭제하며, 이 때 last는 삭제 범위에 포함되지 않는다.

다음은 "This is text sentence"에서 "is text"(공백 포함) 문자열을 삭제하는 예제이다.

#include <algorithm>
#include <string>
#include <iostream>
using namespace std;

int main(){
	string str = "This is test sentence";
	// iterator erase(const_iterator first, const_iterator last);
	// (first, last] 에 해당하는 문자를 제거한다. 즉, last는 제거하지 않는다.
	// ... delete "is test "
	str.erase(str.begin() + 5, str.begin() + 13);
	cout << str << endl;
	return 0;
}
[실행결과] This sentence

 

#2.4 erase & find _ 특정 문자를 탐색하여 제거

string::erase 함수와 string::find 함수를 같이 사용하면 원하는 문자를 탐색해 제거할 수 있다.

string::find 함수는 특정 문자열에서 원하는 문자를 찾을 때 사용하는 함수로, 탐색에 성공 시 찾고자 하는 문자의 첫 번째 이터레이터를 반환한다. _about find function

다음은 "Hello, C++!" 문자열에서 ","(콤마)를 탐색해 제거한 예제이다.

#include <algorithm>
#include <string>
#include <iostream>
using namespace std;

int main(){
	// erase & find function 
	// Hello, C++! -> Hello C++!
	string str = "Hello, C++!";
	str.erase(find(str.begin(), str.end(), ','));
	cout << str << endl;	
	return 0;
}
[실행결과] Hello C++!
반응형

댓글

Designed by JB FACTORY