2010-10-21 43 views
2

情況之間的路徑 「差」:獲得兩個目錄

我有一個或一個以上的絕對路徑,如:

  1. /家庭/本傑明/測試/
  2. /家/本傑明/測試/ A/1
  3. /家庭/本傑明/測試/ b/1

我怎樣才能獲得差異兩條路徑之間?比方說,我想知道我怎麼可以從路徑1到路徑2預期的結果將是

/家庭/本傑明/測試/ A/1 - /主頁/本傑明/測試/ =/A/1

是否有比從對方減去字符串更優雅的方式?

回答

2

我會嘗試使用std::mismatchdocumentation

template <class InputIterator1, class InputIterator2> 
    pair<InputIterator1, InputIterator2> 
    mismatch (InputIterator1 first1, InputIterator1 last1, 
       InputIterator2 first2); 

Return first position where two ranges differ 

比較元素在對那些該範圍內的範圍[first1,last1)first2順序開始,並且其中第一個不匹配發生的回報。

某些代碼:

string 
mismatch_string(string const & a, string const & b) { 

    string::const_iterator longBegin, longEnd, shortBegin; 

    if(a.length() >= b.length()) { 
     longBegin = a.begin(); 
     longEnd = a.end(); 
     shortBegin = b.begin(); 
    } 
    else { 
     longBegin = b.begin(); 
     longEnd = b.end(); 
     shortBegin = a.begin(); 
    } 

    pair< string::const_iterator, string::const_iterator > mismatch_pair = 
     mismatch(longBegin, longEnd, shortBegin); 

    return string( mismatch_pair.first, longEnd); 
} 

full example with outpu噸在鍵盤上傳。

1

我不知道一個電話XXXX(...)的方式,但由於文件路徑樹,我還以爲一個tree traversal algorithm將優雅,因爲它得到...

有東西在這裏在this question

0

您可以將所有路徑插入到Trie中,並查看剩餘的後綴。

稍微普遍一點的是使用edit distance,並且回退最小編輯距離的步驟。

兩者對我來說都顯得更加優雅。但是,首先減去字符串有什麼問題?

0

假設你不擔心諸如/home/benjamin/test/c/..這樣的事情,那麼這將成爲一個簡單的子串匹配練習。

最懶惰的方法是使用類似std::string::find的東西。或者,一個小的while循環遍歷兩個字符串,直到達到一個字符的末尾,或者找到一個字符差異。

1

你可以用一個簡單的正則表達式做到這一點:

return($1) if longer =~ /^#{shorter}(.*)$/ 

這裏是一個complete example in Ruby。你可以在命令行中對它進行測試並開始使用它,或者這段代碼可以讓你知道如何在C++中編寫正則表達式。