Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I partition a QByteArray efficiently?

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;
}
like image 926
gehad Avatar asked Feb 25 '23 05:02

gehad


2 Answers

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);
  }
like image 179
JadziaMD Avatar answered Feb 26 '23 17:02

JadziaMD


Why not make it a regular QString and use split. That will give you a QStringList.

like image 24
Bart Avatar answered Feb 26 '23 17:02

Bart