다음은 특정 단어 (문자열)의 모든 인스턴스를 부모 문자열의 다른 단어 (strng)로 대체하는 함수입니다.while 루프를 do while 루프로 변환
void clean(std::string &s,const std::string oldVal,const std::string newVal){
std::string::size_type pos = 0;
while((pos = s.find(oldVal,pos)) != std::string::npos){
s.replace(pos,oldVal.size(),newVal);
pos += newVal.size();
}
}
저는 C++을 처음 접했고 약간의 이해가 어려웠습니다. 그래서이 코드를 더 읽기 쉽게 만들 생각입니다. 나는 do while 루프로 만들려고했다. 그러나 프로그램이 중단되었습니다. out_of_range 예외를 Throw합니다.
내 코드에 어떤 문제가 있습니까? 같은 문자열을 사용하여 두 기능을 모두 확인했습니다.
void clean2(std::string &s,const std::string oldVal,const std::string newVal){
std::string::size_type pos = 0;
do{
pos = s.find(oldVal,pos);
s.replace(pos,oldVal.size(),newVal);
pos += newVal.size();
}while(pos != std::string::npos);
}
'do-while' 루프에서, 사용하기 전에'pos'를 체크 할 필요가 있습니다. –
나는 while 조건에서 확인하고 있습니다. –
'replace' 함수에'pos'를 사용하고 추가하기 전에 말입니다. –