2

I have seen one answer regarding to this same question but when I tried it with my problem it get confused.

here is my string,

bit_rate = "bitrate: 2334 kb/s"

I need to get the 2334 from this string and assign it into a integer variable.. how is this possible in qt creator. I tried toInt(), but it always gives 0 as the answer.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
Mlarnt90
  • 176
  • 1
  • 4
  • 19
  • 1
    possible duplicate of [How to convert QString to int?](http://stackoverflow.com/questions/16633555/how-to-convert-qstring-to-int) – Eitan T Jul 08 '14 at 11:41
  • no thats the answer I mentioned above.but I couldn't use it as it is.due to suffix and prefix problem – Mlarnt90 Jul 08 '14 at 11:49

3 Answers3

6

You need to get rid of the bitrate: prefix and kb/s suffix. The best way is to use QRegExp or QRegularExpression to extract the digit part of the string and then call toInt().

Here's example:

QString str = "bitrate: 3543 kb/s";
int value;

QRegExp re("bitrate:\\s*(\\d+)\\s*.*");
if (re.indexIn(str) != -1) {
    value = re.cap(1).toInt();
} else {
    qDebug() << "String not matched.";
    return;
}
qDebug() << value;
Googie
  • 5,742
  • 2
  • 19
  • 31
2

The reference page has a ton of material on this. The easiest way to implement this is to split the string based on spaces, then convert the one you want to an Int.

Example:

QString str = "bitrate: 3543 kb/s";
QStringList lst = str.split(" ");
Int value = lst[1].toInt();
kwierman
  • 441
  • 4
  • 11
1
QTextIStream stream("bitrate: 3543 kb/s");
QString prefix, sufix;
int result;
stream >> prefix >> result >> sufix;
Marek R
  • 32,568
  • 6
  • 55
  • 140