【问题标题】:How can I convert a QString of numbers to an array of int?如何将 QString 数字转换为 int 数组?
【发布时间】:2012-12-19 22:14:26
【问题描述】:

我有一个QString,例如包含一系列数字

QString path = "11100332001 234 554 9394";

我想遍历变长字符串

for (int i=0; i<path.length(); i++){

}

并且能够单独以int 的形式访问每个号码。

但是,我无法这样做。 问题:如何将QString 的数字转换为int 的数组?

我知道我可以使用path.toInt()QString 转换为int,但这对我没有帮助。

首先尝试将其转换为 char 时出现错误:cannot convert 'const QChar to char'

for (int i=0; i<path.length(); i++){
        char c = path.at(i);
        int j = atoi(&c);
        //player->movePlayer(direction);
    }

【问题讨论】:

    标签: c++ qt type-conversion qstring


    【解决方案1】:

    您可以使用split 来获取由您想要的分隔符分隔的子字符串数组,在这种情况下它是一个空格,这是一个示例:

    QString str("123 457 89");
    
    QStringList list = str.split(" ",QString::SkipEmptyParts);
    
    foreach(QString num, list)
        cout << num.toInt() << endl;
    

    【讨论】:

    • 比起@antoyo 的答案,我更喜欢这个答案,因为它不那么麻烦
    【解决方案2】:

    您可以使用 [] 运算符获取每个字符 (QChar),然后对它们使用 digitValue() 方法来获取整数。

    【讨论】:

    • @ThomasVerbeke:在这种情况下,您应该使用绿色复选标记将此答案标记为解决方案。
    • 为什么投反对票?这回答了@Thomas 提出的问题。
    【解决方案3】:

    使用QTextStream:

    QString str = "123 234   23123  432";
    QTextStream stream(&str);
    QList<int> array;
    while (!stream.atEnd()) {
        int number;
        stream >> number;
        array.append(number);
    }
    

    【讨论】:

    • 它是;严格来说是;你的答案是完全正确的,但这不是我问题的答案,所以我猜你想说的是我的标题不够具体?足够公平
    • 好的,那你的问题是什么?
    • 我想访问 QString 中一系列数字的各个数字;感谢更改标题。
    【解决方案4】:

    我自己使用了 Antoyo 的答案,但我今天遇到了一个问题。 digitValue() 与使用 atoi 比较 C 中的字符不同,就像 Thomas 试图做的那样。所以当托马斯试图这样做时:

    for (int i=0; i<path.length(); i++){
            char c = path.at(i);
            int j = atoi(&c);
            //player->movePlayer(direction);
        }
    

    使用 digitValue() 会变成这样:

    for (int i=0; i<path.length(); i++){
            int j = path.at(i).digitValue();
            //player->movePlayer(direction);
        }
    

    但是,如果字符串中有任何字母,这不会产生预期的结果。例如,在 C 语言中,如果字符串混合了字母和数字,那么您使用 atoi 的任何字符都将返回 0 来代替字母。但是 digitValue() 不会为字母返回 0。如果您对字符串中结尾的字母有任何顾虑,那么首先检查 isDigit() 可能是个好主意,最终结果如下所示:

    int j = 0;
    for (int i=0; i<path.length(); i++){
            if (path.at(i).isDigit())
                j = path.at(i).digitValue();
            else
                j = 0;
            //player->movePlayer(direction);
        }
    

    这可能不是 OP 关心的问题,但由于这是从 QT 中的字符串获取数字的最佳 Google 结果之一,它可能对其他人有所帮助,尤其是当您试图让 QT 应用程序正常运行时与设备上的一些嵌入式 C 代码相同。

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多