2017-01-03 5 views
0

각 문자열에서 각 문자의 위치를 ​​기반으로 두 텍스트 문자열의 차이를 계산해야합니다. 한 문자열에서 다음 문자열까지 제거 된 텍스트와 삽입 된 텍스트를 찾아야합니다. 예를 들어 'Caty'와 'Bat'을 비교하면 위치 1의 'C'가 제거되고 위치 4의 'y'가 제거되고 위치 1에 'B'가 삽입되고 위치 4에는 2 개의 공백이 삽입되어야 함을 나타냅니다.두 문자열을 비교하는 위치

나는 다음을 시도했지만 시퀀스는 정렬되지 않았고 시각적 인 C++은 iterator 디버깅이 활성화 된 팝업 대화 상자에서이를 나타냅니다. 나는 세트 차 작업을 적용하기 전에 그들을 분류 할 수 있지만, 내가 찾던 것이 아니었을 것이다. 이상적으로는 간단한 표준 : : 문자열 대 문자의 벡터를 사용하여이 작업을 수행하고 싶지만 내가

std::vector<char> cat = {'C', 'a', 't', 'y'}; 
std::vector<char> bat = {'B', 'a', 't', ' ', ' '}; 
std::vector<char> removed; 
std::set_difference(
    bat.begin(), bat.end(), 
    cat.begin(), cat.end(), 
    std::back_inserter(removed)); 
std::cout << removed << std::endl; 
std::vector<char> inserted; 
std::set_difference(
    bat.begin(), bat.end(), 
    cat.begin(), cat.end(), 
    std::back_inserter(inserted)); 
std::cout << inserted << std::endl; 

는 다음 나는이 시도> 문자 또는 표준 : : 벡터 중 하나 벡터에 충실 할 수 있다는 생각 - 하지만 효과적입니다 - 과도한 것처럼 보이는 세트를 사용하도록 강요합니다 - 문자열과 비슷한 것을하는 간단한 방법이 있어야합니다.

std::set<std::pair<int, char>> cat = {{0, 'C'}, {1, 'a'}, {2, 't'}, {3, 'y'}}; 
std::set<std::pair<int, char>> bat = {{0, 'B'}, {1, 'a'}, {2, 't'}, {3, ' '}, {4, ' '}}; 
std::set<std::pair<int, char>> removed; 
std::set_difference(
    cat.begin(), cat.end(), 
    bat.begin(), bat.end(), 
    std::inserter(removed, removed.end())); 
//std::cout << removed << std::endl; 
std::set<std::pair<int, char>> inserted; 
std::set_difference(
    bat.begin(), bat.end(), 
    cat.begin(), cat.end(), 
    std::inserter(inserted, inserted.end())); 
//std::cout << inserted << std::endl; 
+1

당신이'표준 : string'을 사용하지 않는 이유? –

+0

@ThomasMatthews 그러나 문자열에 대한 집합 연산을 적용하면 위치 기반 차이가 나타나지 않습니다. – johnco3

+1

http://stackoverflow.com/questions/805626/diff-algorithm, http://stackoverflow.com/questions/15303631/ 비교할만한 두 개의 문자열을 갖는 what-are-some-algorithms-algorithms-은 –

답변

0

이 유용 할 수 있습니다

std::vector<std::pair<unsigned,char>> string_diff(const std::string& stra,const std::string& strb) { 
    unsigned p = 1; 
    std::vector<std::pair<unsigned,char>> ret; 
    std::for_each(stra.begin(), stra.end(),[&](const char l) { 
     if(strb.find(l) == std::string::npos) { 
      ret.push_back(std::make_pair(p,l)); 
     } 
     p++; 
    }); 

    return ret; 
} 

std::string cat = "caty"; 
std::string bat = "bat "; 

auto removed = string_diff(cat,bat); 
print(removed); 

auto inserted = string_diff(bat,cat); 
print(inserted);