我有不同类型的字符串,我需要找出此字符串中的重复条目。 不同类型的字符串
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;
}
}
谢谢,
答案 0 :(得分:1)
这是一个算法:
在逗号上拆分输入。您将创建以逗号分隔的所有内容的列表。然后,您将从列表中创建可能包含重复项的集。这将删除所有重复项。如果列表的长度等于集合的长度,则没有重复。否则,构造集合会删除重复项,并且它比列表短。
这是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';
}