-1

I'm new in QT and not that new in C++. and although I'm not that good of a programmer I try. This time I can't figure a way to.

I'll be doing a QT application and I'll be having data in the form of

[1 2 45 345 98 452]

(It could be either that or [1,2,45,345,98,452], don't know what will be easier)

and I need the numbers stored in an array So i need to separate the 1 from the 2 from the 45 and so on, and also to know how many numbers there are.

Any ideas? So far I've separated the numbers from the brackets.

2 Answers2

0

Never mind guys, just figured it out. Look

QString myString ="[1 0 12 8 0 12 134]"; //Let's say in data
qDebug() << myString.count(QLatin1Char(' ')); //Counting how many spaces
int size = myString.count(); 
qDebug() << size;
QString newString = myString.mid(1,size-2); //My new string without the []


QRegExp sep("( |,|[|])"); //Regex thingy separating stuff
QStringList list = newString.split(sep);
qDebug() << list;  // TA DA!

Are there fancier ways to achieve this? THANKS

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
0

A way would be to use QRegularExpression with \d+ and iterate over each number. Then you can save the result in a QVector<int>.

Note that QRegExp is deprecated in Qt 5+

QString number = "[1 2 45 345 98 452]";
QRegularExpression rx("\\d+");
QRegularExpressionMatchIterator i = rx.globalMatch(number);
QVector<int> vec1;
while (i.hasNext()) {
    QRegularExpressionMatch match = i.next();
    vec1.append(match.captured(0).toInt());
}
qDebug() << vec1;

Output QVector(1, 2, 45, 345, 98, 452)

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
user3606329
  • 2,405
  • 1
  • 16
  • 28
  • Would you mind explaining to me what each part of the code does? I've been looking at the documentation but it is quite confusing. Thanks mate. – Memo Guerrero Apr 21 '18 at 06:56
  • Memo Guerrero: the code iterates over digits one-by-one in a string. `\d+` is the regex for digits only. Then the code writes the captured numbers in the vector. So you can access the numbers with `for(auto n : vec1) { qDebug() << n; }` or `qDebug() << vec1.at(index);`. The code works also with `[1,2,45,345,98,452]`. – user3606329 Apr 21 '18 at 06:59