Program Language/C & C++

[C++] string 공백 문자 제거

야곰야곰+책벌레 2022. 8. 2. 11:32
728x90
반응형

string에서 특정 문자를 제거하려면 erase 함수를 사용해야 한다.

좌측 문자열을 제거하기 위해서는 erase ( 시작 위치, 개수)를 사용하고, 우측 문자열을 제거하기 위해서는 rease (크기)를 사용한다.

text.erase(0, npos);
text.erase(npos);

특정 문자를 제거하기 위해서는 해당 문자가 아닌 위치를 우선 찾아야 한다. 이때 좌측부터 찾을 때에는 find_first_not_of를 우측부터 찾을 때에는 find_last_not_of를 사용한다.

npos = text.find_first_not_of(' ');
npos = text.find_last_not_of(' ');

두 함수를 이용하여 좌측, 우측 공백 문자를 제거해보자.

	string text("    shared ptr test!!     ");
	cout << text.c_str() << endl;
	int npos;
	
	npos = text.find_first_not_of(' ');
	text.erase(0, npos);
	cout << text.c_str() << "(" << text.size() << ")\n";

	npos = text.find_last_not_of(' ');
	text.erase(npos+1);
	cout << text.c_str() << "(" << text.size() << ")\n";

전체에서 특정 문자를 제거하기 위해서는 <alogrithm>을 추가한 뒤, remove 함수를 사용해야 한다.

	string text2("    shared ptr test!!     ");
	text2.erase(remove(text2.begin(), text2.end(), ' '), text2.end());
	cout << text2.c_str() << "(" << text2.size() << ")\n";

전체 코드는 아래와 같다.

#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
	string text("    shared ptr test!!     ");
	cout << text.c_str() << endl;
	int npos;
	
	npos = text.find_first_not_of(' ');
	text.erase(0, npos);
	cout << text.c_str() << "(" << text.size() << ")\n";

	npos = text.find_last_not_of(' ');
	text.erase(npos+1);
	cout << text.c_str() << "(" << text.size() << ")\n";

	string text2("    shared ptr test!!     ");
	text2.erase(remove(text2.begin(), text2.end(), ' '), text2.end());
	cout << text2.c_str() << "(" << text2.size() << ")\n";

	return 0;
}
728x90
반응형