I have two lists. Both containing the same values:
QStringList filePaths;
filePaths.append("C:/backup");
filePaths.append("C:/download/file1");
filePaths.append("D:");
filePaths.append("C:/program");
filePaths.append("C:/download");
QStringList refinedPaths;
int size = filePaths.size();
for(int i = 0; i < size; i++)
{
refinedPaths.append(filePaths.at(i));
}
for(int i = 0; i < size; i++)
{
QString str1 = filePaths.at(i);
for(int j = 0; j < size; j++)
{
QString str2 = filePaths.at(j);
if(str2 == str1)
{
continue;
}
if(str2.startsWith(str1))
{
refinedPaths.removeAll(str2);
}
}
}
What I’m expecting to happen is:
* Iterate through the strings in list, comparing every item in the list with each other.
* If string1 starts with string2 (string2 is therefore the parent directory of string1)
* remove that string from the ‘refined’ stringlist.
Howver, what is happening is that if(str2.startsWith(str1)) is returning true every time, and refinedPaths.removeAll(str2); doesn’t remove any of the strings in the list.
Any ideas?
Your code works fine, not sure what problem you are referring to. Using your code here’s the output I got
A few things to improve,
instead of copying QStringList element by element you can just use the copy constructor i.e copying from filePaths to refinedPaths
QStringList refinedPaths(filePaths);use iterators instead of iterating by size().