我的来源中有一个 QString
。
所以我需要将它转换为整数没有“Kb”。
我试过 Abcd.toInt()
但它不起作用。
QString Abcd = "123.5 Kb"
最佳答案
您的字符串中没有所有数字字符。所以你必须按空间分割
QString Abcd = "123.5 Kb";
Abcd.split(" ")[0].toInt(); //convert the first part to Int
Abcd.split(" ")[0].toDouble(); //convert the first part to double
Abcd.split(" ")[0].toFloat(); //convert the first part to float
更新:我正在更新旧答案。这是对特定问题的直截了当的回答,并带有严格的假设。但是,正如@DomTomCat 在评论中和@Mikhail 在回答中所指出的那样,通常应该始终检查操作是否成功。所以使用 bool 标志是必要的。
bool flag;
double v = Abcd.split(" ")[0].toDouble(&flag);
if(flag){
// use v
}
此外,如果您将该字符串作为用户输入,那么您还应该怀疑该字符串是否真的可以用空格分割。如果假设有可能被打破,那么正则表达式验证器更可取。像下面这样的正则表达式将提取浮点值和 'b' 的前缀字符。然后你可以安全地将捕获的字符串转换为 double 。
([0-9]*\.?[0-9]+)\s+(\w[bB])
你可以有一个像下面这样的实用函数
QPair<double, QString> split_size_str(const QString& str){
QRegExp regex("([0-9]*\\.?[0-9]+)\\s+(\\w[bB])");
int pos = regex.indexIn(str);
QStringList captures = regex.capturedTexts();
if(captures.count() > 1){
double value = captures[1].toDouble(); // should succeed as regex matched
QString unit = captures[2]; // should succeed as regex matched
return qMakePair(value, unit);
}
return qMakePair(0.0f, QString());
}
关于c++ - 如何将 QString 转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16633555/