1

I've seen a lot on the internet and stakoverflow about parsing a space separated string variable but nothing on parsing a space seperated QString variable on qt I would really appreciate any insight on how to do this.

For example if I had a QString of "Bob 1, 2, 3" and wanted to set name="Bob" num1=1, num2=2, and num3=3.

user3183403
  • 63
  • 1
  • 2
  • 8
  • Have a look at [QTextStream](http://qt-project.org/doc/qt-4.8/qtextstream.html), that's what can be found as a prominent hit googling for **[qt string streams](https://www.google.de/search?q=qt+string+streams&ie=utf-8&oe=utf-8&rls=org.mozilla:en-US:official&client=firefox-a&gws_rd=cr&ei=i23lUp2tHMjNtQadm4DoCQ)** You should definitely try to improve your google fu!! – πάντα ῥεῖ Jan 26 '14 at 20:21

1 Answers1

11
QString str = "Bob 1, 2, 3";

QRegExp rx("[, ]");// match a comma or a space
QStringList list = str.split(rx, QString::SkipEmptyParts);

qDebug() << list;

QString name = list.at(0);
QList <int> nums;
for(int i = 1; i < list.size(); i++)
{
    nums.append(list.at(i).toInt());
}

qDebug() << "Name:" << qPrintable(name);
//    foreach(int num, nums)
//    {
//        qDebug() << "num:" << num;
//    }
for(int i = 0; i < nums.size(); i++)
{
    qDebug() << qPrintable("num" + QString::number(i+1) + ":") << nums.at(i);
}

output

("Bob", "1", "2", "3") 
Name: Bob 
num1: 1 
num2: 2 
num3: 3 
phyatt
  • 18,472
  • 5
  • 61
  • 80