PDA

View Full Version : Creating variable name in Qt by a for loop and finding numbers in a QString object



Alex22
4th December 2015, 19:18
Hi
I have some questions about QString.

1- I want to create a variable name (QString type) in a for loop. how can i do this. like this:

QString name[15];
for(int i=0; i<10; ++i)
name(i) = "name i" //I need "i" in the "name i" be effected

2- In a QString like str (str is a type of QString), I want to find numbers. is there any function that search number in a QString? for example:


QString str;
str="Hi4Hello78good5"
str.isThereSearchNumberFunction(); // I need this returns 4,7,8,5

Thanks for any help.

ChrisW67
4th December 2015, 19:44
QString name[15];
for ( int i = 0; i < 10; ++i)
name[i] = QString("name %1").arg(i);

You should consider a QStringList instead of a C array.

QString::contains() with QRegExp()

Alex22
4th December 2015, 19:55
QString name[15];
for ( int i = 0; i < 10; ++i)
name[i] = QString("name %1").arg(i);

You should consider a QStringList instead of a C array.

QString::contains() with QRegExp()

Realy thanks, ChrisW67
For what must I consider QStringList? QString is not good class for this target?
I need if str has any number, return that numbers, not true or false. QString::contains() with QRegExp() returns true or false. Is there any function for QString or must write it myself?

ChrisW67
4th December 2015, 20:23
A QStringList might be a good alternative to a fixed length array of strings.

If you want the captured string(s) then just use QRegExp to capture the matches. There is a useful example in the docs.

Alex22
4th December 2015, 20:37
A QStringList might be a good alternative to a fixed length array of strings.

If you want the captured string(s) then just use QRegExp to capture the matches. There is a useful example in the docs.

Realy nice!!! this example is exactly that i want!

QRegExp rx("(\\d+)");
QString str = "Offsets: 12 14 99 231 7";
QStringList list;
int pos = 0;

while ((pos = rx.indexIn(str, pos)) != -1) {
list << rx.cap(1);
pos += rx.matchedLength();
}
// list: ["12", "14", "99", "231", "7"]

so many thanks ChrisW67!!!

anda_skoa
5th December 2015, 11:22
If you are on Qt5 you might want to use the new QRegularExpression class instead of QRegExp, to make your code more future proof

Cheers,
_