If you're really concerned about performance you could use QString::indexOf() and the lightweight wrapper QStringRef.
QStringRef avoids the memory allocation and reference counting overhead of a standard QString by simply referencing a part of the original string. This can prove to be advantageous in low level code, such as that used in a parser, at the expense of potentially more complex code.
The code would look something like this:
QVector<QStringRef> fields(MAX_FIELDS);
{
int start=0, end=0, validFields=0;
while(validFields < MAX_FIELDS && (end=line.indexOf(',', start)) != -1)
{
fields[validFields++] = QStringRef(&line, start, end-start);
start=end+1;
}
if(validFields < MAX_FIELDS && start<=line.size())
fields[validFields++] = QStringRef(&line, start, line.size()-start);
// fields now contain 'validFields' valid entries(some of which might be empty)
}
QVector<QStringRef> fields(MAX_FIELDS);
foreach(QString line, ...)
{
int start=0, end=0, validFields=0;
while(validFields < MAX_FIELDS && (end=line.indexOf(',', start)) != -1)
{
fields[validFields++] = QStringRef(&line, start, end-start);
start=end+1;
}
if(validFields < MAX_FIELDS && start<=line.size())
fields[validFields++] = QStringRef(&line, start, line.size()-start);
// fields now contain 'validFields' valid entries(some of which might be empty)
}
To copy to clipboard, switch view to plain text mode
Bookmarks