2016-07-15 199 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. 的我無法找出適合入門字符串「字符串而aStr =‘1.1,1.2,1.3,1’解決方案; 請幫我找出解決辦法。

感謝,

+0

是什麼讓你無法?你遇到什麼具體問題? –

+0

你爲什麼明確地處理'.'?該算法看起來很簡單:用逗號分隔。從分割列表創建一個集合。如果這個集合的長度等於分割列表的長度,那麼不會有任何愚蠢的行爲。 – erip

+0

請把這個任務的文本放在這裏。例如,定義「重複」。 – Les

回答

1

這裏有一個算法:

拆分的逗號,輸入您將創建一切都很列表g是用逗號分隔的。然後,您將從列表中創建一個可能包含重複項的集合。這會爲您刪除所有重複項。如果列表的長度等於集合的長度,則不會有重複。否則,構建集合刪除重複項,並且比列表短。


這是C++中的代碼。我從this answer拿來了標記,並做了一些修改。另外,這裏是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

它運行在所有情況下,但它在std失敗:: string dupes =「1.1,2.1,3,4,1」; 這個字符串也有重複。 – CrazyCoder

+1

@CrazyCoder該字符串沒有重複項。 1.1,2.1,3,4和1都是不同的數字...... – erip

相關問題