코테 대비 c++ 문자열 처리 - 2 ReplaceAll

박기정·2021년 7월 27일
0

이번에는 저번 포스트에서 이용한 replace를 이용하여 문자열에서 특정 문자열을 찾아 모두 치환하는 함수를 소개한다.

Find를 이용한 ReplaceAll

std::string ReplaceAll(std::string &str, const std::string& from, const std::string& to) {

	size_t start_pos = 0; //string처음부터 검사

	while ((start_pos = str.find(from, start_pos)) != std::string::npos)  //from을 찾을 수 없을 때까지

	{

		str.replace(start_pos, from.length(), to);

		start_pos += to.length(); // 중복검사를 피하고 from.length() > to.length()인 경우를 위해서

	}

	return str;

}

참고: https://blog.daum.net/andro_java/801

0개의 댓글

관련 채용 정보