Ber
Ber

Reputation: 41813

efficiently compare QString and std::string for equality

I want to efficiently compare a QString and a std::string for (in)equality. Which is the best way to do it, possibly without creating intermediate objects?

Upvotes: 9

Views: 9352

Answers (2)

Dan Milburn
Dan Milburn

Reputation: 5718

It can be done without intermediate objects, if you are absolutely sure that the two strings contain only Latin characters:

bool latinCompare(const QString& qstr, const std::string& str)
{
  if( qstr.length() != (int)str.size() )
    return false;
  const QChar* qstrData = qstr.data();
  for( int i = 0; i < qstr.length(); ++i ) {
    if( qstrData[i].toLatin1() != str[i] )
      return false;
  }
  return true;
}

Otherwise you should decode the std::string into a QString and compare the two QStrings.

Upvotes: 0

Shf
Shf

Reputation: 3493

QString::fromStdString() and QString::toStdString() comes to mind, but they create temporary copy of the string, so afaik, if you don't want to have temporary objects, you will have to write this function yourself (though what is more efficient is a question).

Example:

    QString string="string";
    std::string stdstring="string";
    qDebug()<< (string.toStdString()==stdstring); // true


    QString string="string";
    std::string stdstring="std string";
    qDebug()<< (str==QString::fromStdString(stdstring)); // false

By the way in qt5, QString::toStdString() now uses QString::toUtf8() to perform the conversion, so the Unicode properties of the string will not be lost (qt-project.org/doc/qt-5.0/qtcore/qstring.html#toStdString

Upvotes: 5

Related Questions