2013-05-28 4 views
1

문자열을 대체하는 함수를 만들었습니다.문자열에서 C++ 오류가 발생했습니다.

그것은 다음과 같습니다

void replace_with(wstring& src, const wstring& what, const wstring& with) 
{  
    if (what != with) { 
     wstring temp; 
     wstring::size_type prev_pos = 0, pos = src.find(what, 0); 
     while (wstring::npos != pos) { 
      temp += wstring(src.begin() + prev_pos, src.begin() + pos) + with; 
      prev_pos = pos + what.size(); 
      pos = src.find(what, prev_pos); 
     } 
     if (!temp.empty()) { 
      src = temp + wstring(src.begin() + prev_pos, src.end()); 
      if (wstring::npos == with.find(what)) { 
       replace_with(src, what, with); 
      } 
     } 
    } 
} 

을하지만, 내 캐릭터의 크기 == 1이며,이 문자열이 exactely이다 "무엇을", 그것을 대체하지 않습니다. "-"예를

wstring sThis=L"-"; 
replace_with(sThis,L"-",L""); 

를 들어

합니다 ...를 대체하지 않습니다.

내가 잘못 된 부분이 보이지 않습니다.

아무도 도와 줄 수 있습니까?

+2

위의 내용은 순전히 학습 연습 이었지만 다른 점은 왜 ['std :: string :: replace'] (http://en.cppreference.com/w/cpp/string/basic_string/replace)? – BoBTFish

답변

1

기능의 주요 부분이 정상적으로 작동합니다. 문제는 if (! temp.empty()) 부분입니다. 이는 절대 의미가 없습니다. 전체 if 블록을 줄 바꿈으로 바꿉니다.

src = temp + wstring(src.begin() + prev_pos, src.end()); 

잘 작동합니다.

힌트 : 함수의 마지막 부분에서 수행중인 작업을 단어로 설명하십시오.

2
void replace_with(wstring &src, wstring &what, wstring &with) { 
    for (size_t index = 0; (index = src.find(what, index)) != wstring::npos ;) { 
     src.replace(index, what.length(), with); 
     index += with.length(); 
    }  
} 
관련 문제