2013-11-26 3 views
0

std :: string의 replace를 사용하려고했지만 성공적으로 수행 할 수 없었습니다.std :: string이 시작과 끝 사이를 바꿉니다

나는 약간의 교체를하고 싶은 큰 문자열이 있습니다. 새 문자열로 대체해야하는 부분 문자열의 시작과 끝을 알고 있습니다.

static void replaceString(string &input, const string &startString, const string &endString, const string &replacement) 
{ 
    size_t indexStart, indexEnd; 

    indexStart = input.find(startString); 
    indexEnd = input.find(endString); 
    if (indexStart != xml.npos) { 
     input.replace(indexStart, indexEnd-indexStart, replacement); 
    } 
} 

마지막에는 입력이 변경되지 않습니다.

여기서 내가 뭘 잘못하고 있니?

감사

+1

(indexStrat! = xml.npos) if line if if line. –

+0

함수에 어떤 입력 사항이 있습니까? 그리고 만약'endString'을 찾을 수 없다면? –

+0

xml은 오타였습니다. 입력입니다. – chingupt

답변

1

을 내가 그것을보고, 두 검사가 누락 :

  1. endString 경우는
  2. endString 경우이 경우,startString 전에 를 발견, 발견되지 않는, 당신의 뺄셈을에 replace()의 두 번째 매개 변수를 계산하면 오버플로 할 길이가 음수가됩니다.

또한 일치가 있는지 여부를 확인하기 위해 부울 값을 반환 할 수 있습니다.

이 대신 같은 것을보십시오 :

static bool replaceString(string &input, const string &startString, const string &endString, const string &replacement) 
{ 
    size_t indexStart, indexEnd; 
    indexStart = input.find(startString); 
    if (indexStart == input.npos) { 
     return false; 
    } 
    indexEnd = input.find(endString, indexStart); // Note the offset to start searching 
                // after the start index 
    if (indexEnd == input.npos) { 
     return false; 
    } 
    input.replace(indexStart, indexEnd-indexStart, replacement); 
    return true; 
} 

테스트 프로그램 :

int main (int, char**) 
{ 
    string s ("abcdefghijklmnopqrstuvwxyz"); 

    string start ("gh"); 
    string end ("pq"); 
    string replace ("GHIJKLMNO"); 
    bool ok = replaceString(s, start, end, replace); 

    std::cout << "1. found? " << ok << ", result: " << s << std::endl; 

    start = "pq"; 
    end = "de"; 
    ok = replaceString(s, start, end, replace); 

    std::cout << "2. found? " << ok << ", result: " << s << std::endl; 

    return 0; 
} 

출력 :

1. found? true, result: abcdefGHIJKLMNOpqrstuvwxyz 
2. found? false, result: abcdefGHIJKLMNOpqrstuvwxyz 
0

이 답변은 줄리앙-L의 유사하지만 난 당신이 또한 필요하다고 생각 indexStart을 넘겨서 교체하면 찾은 내용 중 어느 것도 덮어 쓰지 않습니다. startString.

static void replaceString(std::string &input, const std::string &startString, const std::string &endString, const std::string &replacement) 
{ 
    size_t indexStart = input.find(startString); 
    if (indexStart == input.npos) return; 
    indexStart += startString.size(); 

    size_t indexEnd = input.find(endString, indexStart); 
    if (indexEnd == input.npos) return; 

    input.replace(indexStart, indexEnd - indexStart, replacement); 
} 
관련 문제