Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pack QStringList to QString and unpack it back

Tags:

c++

qt

qstring

I'm in search for an easy and foolproof way to convert an arbitrary QStringList to a single QString and back.

QStringList fruits;
fruits << "Banana", "Apple", "Orange";
QString packedFruits = pack(fruits);
QStringList unpackFruits = unpack(packedFruits);

// Should be true 
// fruits == unpackFruits;

What might be the easiest solution for this kind of problem?

like image 212
Aleph0 Avatar asked May 31 '16 07:05

Aleph0


People also ask

How do you convert QString to QStringList?

You just need to "split":http://developer.qt.nokia.com/doc/qt-4.8/qstring.html#split the QString. The result is a list of strings.

What is a QStringList?

The QStringList class provides a list of strings. QStringList inherits from QList<QString>. Like QList, QStringList is implicitly shared. It provides fast index-based access as well as fast insertions and removals. Passing string lists as value parameters is both fast and safe.


1 Answers

From QStringList to QString - QStringList::join:

Joins all the string list's strings into a single string with each element separated by the given separator (which can be an empty string).

QString pack(QStringList const& list)
{
    return list.join(reserved_separator);
}

From QString to QStringList - QString::split:

Splits the string into substrings wherever sep occurs, and returns the list of those strings. If sep does not match anywhere in the string, split() returns a single-element list containing this string.

QStringList unpack(QString const& string)
{
    return string.split(reserved_separator);
}
like image 167
LogicStuff Avatar answered Oct 04 '22 04:10

LogicStuff