How to add items from multiple QStringLists to one? - c++

If I have several QStringLists, for example:
QStringList str1 = {"name1", "name2", "name3"};
QStringList str2 = {"value1", "value2", "value3"};
QStringList str3 = {"add1", "add2", "add3"};
Is there any way to get list of lists (nested list) like QStringList listAll; that will look like this:
(("name1","value1","add1"),("name2","value2","add2"),("name3","value3","add3"))

From the comment, it looks like you are trying pack the list of strings to a QVector instead of QList. In that case, do simply iterate through the QStringList s and append the list of strings created from the equal indexes to the vector.
#include <QVector>
QVector<QStringList> allList;
allList.reserve(str1.size()); // reserve the memory
for(int idx{0}; idx < str1.size(); ++idx)
{
allList.append({str1[idx], str2[idx], str3[idx]});
}

you dont need a vector for that, keep using the StringList
QStringList str1={"name1", "name2", "name3"};
QStringList str2={"value1", "value2", "value3"};
QStringList str3={"add1", "add2", "add3"};
QStringList r{};
// use elegantly the << operator and the join method instead... 😃
r << str1.join(",") << str2.join(",") << str3.join(",");
qDebug() << "result : " << r.join(";");
//result:
//"name1,name2,name3;value1,value2,value3;add1,add2,add3"

Related

Extract number from Alphanumeric QString

I have a QString of "s150 d300". How can I get the numbers from the QString and convert it into integer. Simply using 'toInt' is not working.
Let say, from the QString of "s150 d300", only the number after the alphabet 'd' is meaningful to me. So how can I extract the value of '300' from the string?
Thank you very much for your time.
Why all the trouble if you can just do:
#include <QDebug>
#include <QString>
const auto serialNumberStr = QStringLiteral("s150 d300");
int main()
{
const QRegExp rx(QLatin1Literal("[^0-9]+"));
const auto&& parts = serialNumberStr.split(rx, QString::SkipEmptyParts);
qDebug() << "2nd nbr:" << parts[1];
}
Prints out: 2nd nbr: "300"
One possible solution is to use regular expressions as shown below:
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString str = "s150 dd300s150 d301d302s15";
QRegExp rx("d(\\d+)");
QList<int> list;
int pos = 0;
while ((pos = rx.indexIn(str, pos)) != -1) {
list << rx.cap(1).toInt();
pos += rx.matchedLength();
}
qDebug()<<list;
return a.exec();
}
Output:
(300, 301, 302)
Thanks to the comment of #IlBeldus, and according to the information QRegExp will be deprecated, so I propose a solution using QRegularExpression:
Another solution:
QString str = "s150 dd300s150 d301d302s15";
QRegularExpression rx("d(\\d+)");
QList<int> list;
QRegularExpressionMatchIterator i = rx.globalMatch(str);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
QString word = match.captured(1);
list << word.toInt();
}
qDebug()<<list;
Output:
(300, 301, 302)
If your string is split into space separated tokens like the example you gave you can simply get the value out of it by splitting it, then finding a token that meets your needs and then taking the number part of it. I used atoi after converting the qstring into something I'm more comfortable with but I think there's a more efficient way.
Although this isn't as flexible as regular expressions, it should give better performance for the example you provided.
#include <QCoreApplication>
int main() {
QString str = "s150 d300";
// foreach " " space separated token in the string
for (QString token : str.split(" "))
// starts with d and has number
if (token[0] == 'd' && token.length() > 1)
// print the number part of it
qDebug() <<atoi(token.toStdString().c_str() + 1);
}
There are already answers giving a suitable solution to this problem, but I think it might be also helpful to stress that QString::toInt won't work because the string being converted should be a textual representation of a number and in the given example it is an alpha-numeric expression in a non-standard notation, thus it is necessary to manually process it as already suggested in order to make it "understanable" for Qt to perform the convertion.

Search part of a QString in QStringList in Qt

In QString, contains() method works like this:
QString s = "long word";
s.contains("long"); // -> True
I would assume that QStringList works similarly, but it does not:
QStringList s;
s << "long word";
s << "longer word";
s.contains("long"); // -> False
QStringList contains searches for the exact match, which does not work like I want it to. Is there an easy way to find a part of a string in a QStringList? I could of course loop through the QStringList and use contains() there, but is there a better way?
You can use the function QStringList::filter() :
QStringList QStringList::filter(const QString &str,
Qt::CaseSensitivity cs = Qt::CaseSensitive) const
Returns a list of all the strings containing the substring str.
and check that the list returned is not empty.
In your case:
QStringList s;
s << "long word";
s << "longer word";
s.filter("long"); // returns "long word", and also "longer word" since "longer" contains "long"

How to parse QString?

I am trying to parse QString with following code:
QString name = "name.bin";
QStringList imgName = name.split(".");
qDebug() << imgName.at(0); // result is "name"
However I need just name without any ("). Then I write another code to manually delete quotes("").
Is there any easy way to split QString?
There are no " " in the string. It just contains Name
qDebug() << (imgName.at(0))[0]; // result is n

Fastest string find from the list of string

I have a list of strings and I have to find whether a string is present in that list or not. I wanted to use the logic in low latency pricing engine so I wanted to have real fast logic for it.
I thought of having these strings stored in map as keys and then could use find() or count() function for the same.
Can anyone suggest any other more efficient logic for the same?
Probably std::unordered_set is an appropriate choice for your needs. You would then use find() to check if a string is present or not. Something like the example code here:
#include <iostream>
#include <string>
#include <unordered_set>
int main() {
std::unordered_set<std::string> myset{ "red", "green", "blue" };
std::cout << "color? ";
std::string input;
std::cin >> input;
auto pos = myset.find(input);
if (pos != myset.end())
std::cout << *pos << " is in myset\n";
else
std::cout << "not found in myset\n";
}
To understand how std::unordered_set works, please see hash set.
One more way I just now thought of is,
Put the list of string in single semicolon separated string and then use strfind.
e.g.
List of string, <ABC,DEF,GHI,JKL,MNO,PQRS,LMNOPQR, STUVW,XY,Z>
l_czEIDHolder = “ABC;DEF;GHI;JKL;MNO;PQRS;LMNOPQR; STUVW;XY;Z”
if string_to_search = “PQRS”
make string_to_search = string_to_search +”;”
strfind(czEIDHolder, string_to_search) OR
string::find(czEIDHolder, string_to_search)

Qt loop through QHash<QString,QString> to return it's key-value pairs

I'm trying to loop through a QHash using foreach and get each pair in the QHash and then get the keys and values of those so I can append them to a string.
Here's what I have
QString Packet::Serialize() {
QString sBuilder = Command.toUpper() + " ";
foreach(QMap<QString,QString> pair, Attributes) {
sBuilder.append(pair); // i know this isn't right because I couldn't
// finish the statement
}
}
The variable Attributes is the QHash.
Also, I realize the code is probably 100% wrong because I'm converting it from C#.
Looks like you're trying to append each key/value pair to a string? Something like this would work:
QStringList data;
foreach(const QString &key, Attributes.keys())
data << key << Attributes.value(key);
sBuilder += data.join(" ");