Reputation: 630
I have a set of strings that satisfy the following pattern: sometext_number. So, I always have a number after '_' symbol. Is there a convenient way to get that number from a string regardless of its size?
Upvotes: 0
Views: 2092
Reputation: 252
If you are using QString
anyways, you can do
QString s = "sometext_5";
int index = s.indexOf("_");
int number = s.mid(index+1).toInt();
Upvotes: 1
Reputation: 4079
If you are sure that you always have "sometext_number", you can test the following solutions:
Using QString::split()
:
QString str = "hello_1234";
int number = str.split('_').last().toInt();
Using QRegularExpression::match()
:
QString str = "world_5678";
QRegularExpression regex("\\w+_(?<number>\\d+)");
QRegularExpressionMatch m = regex.match(str);
int number = m.captured("number").toInt();
Upvotes: 5
Reputation:
You can use std::find, which returns you the index of the element you're looking at, and then use substr on your string, given in parameter the index where you want to stop splitting
Upvotes: 0