4

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;
}
user229044
  • 232,980
  • 40
  • 330
  • 338
gehad
  • 1,205
  • 3
  • 12
  • 17
  • Related: [How to get substring from a string in qt?](https://stackoverflow.com/questions/23033112/how-to-get-substring-from-a-string-in-qt) – iammilind Oct 21 '19 at 14:23

2 Answers2

5

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);
  }
JadziaMD
  • 2,690
  • 5
  • 31
  • 42
  • Thanks JadziaMD, I had to change it little bit to get it to work the same way I wanted. – gehad May 15 '11 at 07:00
4

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

Vuks
  • 801
  • 1
  • 7
  • 24
Bart
  • 19,692
  • 7
  • 68
  • 77