2016-07-15 30 views
-3

私は異なるタイプの文字列を持っており、この文字列の重複するエントリを調べる必要があります。文字列C++で文字列の重複するエントリを見つける

string aStr= "1.1,1.2,1.3, 1"; //output should be duplicate entry 
string aStr= "1.1,1.2,1.3"; //Ouput NO duplicate entry 
string aStr= "1,2,1"; //o/p duplicate entry 
string aStr = "1,2,3";//output No duplicate 

I have tried as 
std::vector <std::string> aOutString; 
std::set <int> full_list; 
std::set <std::string> aEntryInDouble; 
int aNum1; 
boost::split(aOutString, aStr , boost::is_any_of(",")); 
for(size_t it = 0; it < aOutString.size(); ++it) 
{ 
if (aOutString[it].find('.') != std::string::npos) 
{ 
//If entry is like "1.1,1.2,1.3" 
    if(!aEntryInDouble.insert(aOutString[it]).second) 
    { 
    aDup = false; 
    break; 
    } 
} 
else 
{ 
//For entry "1,2,1" 
aNum1 = std::atoi(aOutString[it].c_str()); 
if(aNum1) 
{ 
if(!full_list.insert(aNum1).second) 
{ 
aDup = false; 
break; 
} 
} 
  1. の 異なるタイプIは、エントリ文字列「文字列ASTR = 『1.1,1.2,1.3、1』のための解決策を見つけることができないのです。 は解決策を見つけるために私を助けてください。

おかげで、

+0

何ができないのですか? _specific_問題が発生しましたか? –

+0

なぜ '.'を明示的に扱っていますか?アルゴリズムは単純なようです:コンマで区切ってください。分割リストからセットを作成します。セットの長さが分割リストの長さと等しい場合は、重複はありません。 – erip

+0

ここに仕事のテキストを入れてください。たとえば、「複製」を定義します。 – Les

答えて

1

ここアルゴリズムです:。

スプリットコンマ上の入力あなたはeverythinのリストを作成します。 gはカンマ区切りです。リストから重複を含むセットを作成します。これにより、すべての複製が削除されます。リストの長さがセットの長さと等しい場合、重複はありません。さもなければ、セットを構築することは複製を削除し、それはリストよりも短くなります。


ここはC++のコードです。私はthis answerからtokenizeを取り出し、いくつか変更しました。また、ここにはcoliruがあります。

#include <iostream> 
#include <vector> 
#include <string> 
#include <unordered_set> 

std::vector<std::string> split(const std::string& str, const std::string& delimiters = ",") { 
    std::vector<std::string> tokens; 

    // Skip delimiters at beginning. 
    auto lastPos = str.find_first_not_of(delimiters, 0); 
    // Find first "non-delimiter". 
    auto pos = str.find_first_of(delimiters, lastPos); 

    while(std::string::npos != pos || std::string::npos != lastPos) { 
     // Found a token, add it to the vector. 
     tokens.push_back(str.substr(lastPos, pos - lastPos)); 
     // Skip delimiters. Note the "not_of" 
     lastPos = str.find_first_not_of(delimiters, pos); 
     // Find next "non-delimiter" 
     pos = str.find_first_of(delimiters, lastPos); 
    } 

    return tokens; 
} 

bool has_dupes(const std::vector<std::string>& v) { 
    std::unordered_set<std::string> s(v.cbegin(), v.cend()); 
    return s.size() != v.size(); 
} 

std::string detect_duplicates(const std::string& s) { 
    auto v = split(s); 
    return has_dupes(v) ? "duplicates" : "no duplicates"; 
} 

int main() { 
    // dupes 
    std::string dupes = "1,2,3,4,1"; 
    std::cout << detect_duplicates(dupes) << '\n'; 

    // no dupes 
    std::string no_dupes = "1,2,3"; 
    std::cout << detect_duplicates(no_dupes) << '\n';   
} 
+0

これはすべてのシナリオで実行されているが、 ::文字列dupes = "1.1,2.1,3,4,1"; この文字列も重複しています。 – CrazyCoder

+1

@CrazyCoderその文字列に重複はありません。 1.1、2.1、3、4、1はすべて異なる数字です... – erip

関連する問題