c++ - 如何将 QString 转换为 int?

标签 c++ string qt int qstring

我的来源中有一个 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/

相关文章:

c# - 将 struct* 从 c# 传递到 c++ dll

c++ - 从十进制转换为 Base R c++

ruby-on-rails - Rails 4 字符串复选框从不返回空数组

python - 无法在图中添加图例

java - 是否有任何 API 允许您在 c/c++ 中调用部分 Android SDK?

c++ - 如何从 QStandardItem 继承?

c++ - 如何在 Windows 控制台中禁用用户选择

c++ - 免费的 C/C++ PDF 创建器库 Linux(不是 libharu)

c++ - 我可以检查缓存中是否有一 block 内存(例如,使用 malloc 分配)吗?

c# - 如何在字符串上添加 `.Take()` 并在末尾获取字符串?