How can I partition a QByteArray efficiently?

回眸只為那壹抹淺笑 提交于 2019-12-04 03:50:20

问题


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

回答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);
  }



回答2:


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



来源:https://stackoverflow.com/questions/5978124/how-can-i-partition-a-qbytearray-efficiently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!