PDA

View Full Version : Splitting QString



Peeri
13th April 2011, 12:59
I have following QString:

aaa="7\n+1000+1500\n+50-300\n-300+200\n8\n"

Now I want to split string to following way:
bb to be one line of text. (first is "7" second is "+1000+1500")

and then if line start with + or - I need split bb to parts
(first is a1=what ever a2=what ever
second line a1="+1000" a2="+1500"
and third line a1="+50" a2="-300" )

I condsider Following code, but I face difficult it separator can be + or -

while (i >= aaa.lenght()) {
needed coode to parse first line to qstring bb (separator is line feed)
i=i+bb.lenght()+1;
if (bb="7") { Fine do something}
else if (bb="7") { Fine do something}
else if (bb.left(1)=="+" || bb.left(1)=="-") {
needed coode to parse split bb to qstrings a1 and a2
}
}

I'm very newbie of c++ so don't give too difficult theoretic answers :confused:

mcosta
13th April 2011, 13:41
You can split a QString using QString::split and use QRegExp for capture part of string matching a pattern



// Split in lines
QStringList lines = aaa.split('\n');
QRegExp re("([+-]\\d*)([+-]\\d*)");

Q_FOREACH (QString line, lines) {
if (re.exactMatch(line)) {
a1 = rx.cap (1);
a2 = rx.cap (2);
// do something with a1 and a2
}
else {
bb = line;
// do something with bb
}
}