文字列から数値を取得する方法は何ですか?

Qtを使用すると、文字列から数値を取得するためにQRegExp、QStringList、またはQStringのいくつかの組み込みメソッドを使用できます。

  1. QRegExpの使用:
QString text = "Hello123World456";
QRegExp regex("\\d+");  // 匹配一个或多个数字
int pos = 0;
while ((pos = regex.indexIn(text, pos)) != -1) {
    QString number = regex.cap(0);  // 获取匹配到的数字
    // 处理数字
    qDebug() << number;
    pos += regex.matchedLength();
}
  1. QStringListを利用する:
QString text = "Hello 123 World 456";
QStringList list = text.split(QRegExp("\\D+"));  // 使用非数字字符分割字符串
foreach (const QString &number, list) {
    if (!number.isEmpty()) {
        // 处理数字
        qDebug() << number;
    }
}
  1. QStringクラスのtoInt()メソッドまたはtoDouble()メソッドを使用してください。
QString text = "Hello 123 World 456";
QString number;
int pos = 0;
while (pos < text.length()) {
    if (text[pos].isDigit()) {  // 找到数字的起始位置
        int startPos = pos;
        while (pos < text.length() && text[pos].isDigit()) {
            pos++;
        }
        number = text.mid(startPos, pos - startPos);  // 截取数字
        // 处理数字
        qDebug() << number;
    }
    pos++;
}

実際のニーズに合わせて適切な方法を選択してください。

bannerAds