How can I partition a QByteArray efficiently?

gehad picture gehad · May 12, 2011 · Viewed 12.8k times · Source

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;
}

Answer

Bart picture Bart · May 12, 2011

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