Archiac Coder
Archiac Coder

Reputation: 166

How to split QString based on a given character length?

I am trying to split QString based on 19 characters per group.

Here is the string:

+1.838212011719E+04-1.779050827026E+00 3.725290298462E-09 0.000000000000E+00

I wish to split it into:

+1.838212011719E+04
-1.779050827026E+00
3.725290298462E-09
0.000000000000E+00

I have tryed using QRegularExpression, but I could not come up with a solution.

How to do this?

Upvotes: 1

Views: 2514

Answers (2)

help-info.de
help-info.de

Reputation: 7260

Use this regular expression:

^(.{19})(.{19})(.{19})(.{19})

I would also recommend using a tool like RegEx101. Give it a try ans see what happens.

enter image description here

Upvotes: 1

scopchanov
scopchanov

Reputation: 8399

Solution

I would suggest you to use a loop instead of a regular expression.

Example

Here is an example I have prepared for you of how to implement this in C++:

bool splitString(const QString &str, int n, QStringList &list)
{
    if (n < 1)
        return false;

    QString tmp(str);

    list.clear();

    while (!tmp.isEmpty()) {
        list.append(tmp.left(n));
        tmp.remove(0, n);
    }

    return true;
}

Note: Optionally you can use QString::trimmed(), i.e. list.append(tmp.left(n).trimmed());, in order to get rid of the leading whitespace.

Result

Testing the example with your input:

QStringList list;

if (splitString("+1.838212011719E+04-1.779050827026E+00 3.725290298462E-09 0.000000000000E+00", 19, list))
    qDebug() << list;

produces the following results:

  • without QString::trimmed()

      ("+1.838212011719E+04", "-1.779050827026E+00", " 3.725290298462E-09", " 0.000000000000E+00")
    
  • with QString::trimmed()

      ("+1.838212011719E+04", "-1.779050827026E+00", "3.725290298462E-09", "0.000000000000E+00")
    

Upvotes: 3

Related Questions