How can I partition a QByteArray efficiently?
13,530
Solution 1
What about this:
QByteArray Server::getPart(const QByteArray& message, int part, bool toEnd)
{
int characters(toEnd ? -1 : message.indexOf(' ', part) - part);
return message.mid(part, characters);
}
Solution 2
Why not make it a regular QString and use split. That will give you a QStringList.
Author by
gehad
Updated on June 04, 2022Comments
-
gehad almost 2 years
I want to partition a QByteArray message efficiently, so this function I implemented take the Bytes, the part I want to extract, and toEnd flag which tells if I want to extract part1 till the end of the array. my dilimeter is spcae ' '
example if I have:
ba = "HELLO HOW ARE YOU?" ba1 = getPart(ba, 1, false) -> ba1 = "HELLO" ba2 = getPart(ba, 2, true) -> ba2 = "HOW ARE YOU?" ba3 = getPart(ba, 3, false) -> ba3 = "ARE"
the function below works just fine, but I am wondering if this is efficient. should I consider using split function?
QByteArray Server::getPart(const QByteArray message, int part, bool toEnd) { QByteArray string; int startsFrom = 0; int endsAt = 0; int count = 0; for(int i = 0; i < message.size(); i++) { if(message.at(i) == ' ') { count++; if(part == count) { endsAt = i; break; } string.clear(); startsFrom = i + 1; } string.append(message.at(i)); } if(toEnd) { for(int i = endsAt; i < message.size(); i++) { string.append(message.at(i)); } } return string; }
-
gehad almost 13 yearsThanks JadziaMD, I had to change it little bit to get it to work the same way I wanted.