c++ 使用 .indexOf 在 QStringList 中查找以 "..." 开头的文本

c++ find text in QStringList that starts with "..." using .indexOf

本文关键字:开头 文本 查找 使用 indexOf QStringList c++      更新时间:2023-10-16

我有一个关于QStringList:的问题

我有一个.txt文件,其中包含1000行数据,然后是:

+-------------------------+-------------------+-----------------------|     
 |  Conditions at          |      X1           |     X2                |     
 +-------------------------+-------------------+-----------------------|     
 |  Time [ms]              |   0.10780E-02     |     0.27636E-02       |     
 |  Travel [m]             |   0.11366E+00     |     0.18796E+01       |     
 |  Velocity [m/s]         |   0.43980E+03     |     0.13920E+04       |     
 |  Acceleration [g]       |   0.11543E+06     |     0.20936E+05       |  
…

其中标题(条件…)和第一列(行程、时间…)始终保持不变,但每次运行的值不同。从这个文件中,我想将值(仅!)读取到GUI的字段中。首先,我将所有数据写入一个QStringList。(将.txt的每一行复制到QStringList的一个元素)

为了获得值,我试图从QStringList中找到带有".indexOf()"的对应行,但没有成功,因为我必须询问整行的确切文本。由于值不同,每次运行的行都不同,我的程序无法找到对应行。

是否有类似".indexOf从特定文本开始"的命令,它会发现行以特定文本开始,例如"|Time[ms]"

非常感谢

itelly

是的,有方法".indexOf从特定文本开始"。您可以使用正则表达式来匹配字符串的开头:

 int QStringList::indexOf (const QRegExp& rx, int from = 0) const

以这种方式使用:

int timeLineIndex = stringList.indexOf(QRegExp("^|  Time [ms].+"));

^表示此文本应位于字符串的开头
转义特殊字符
.+表示任何文本都可以跟随此

编辑:
下面是一个工作示例,展示了它的工作原理:

QStringList stringList;
stringList << "abc 5234 hjd";
stringList << "bnd|gf dfs aaa";
stringList << "das gf dfs aaa";
int index = stringList.indexOf(QRegExp("^bnd|gf.+"));
qDebug() << index;

输出:1

编辑:

这里有一个ezee使用的函数:

int indexOfLineStartingWith(const QStringList& list, const QString& textToFind)
{
  return list.indexOf(QRegExp("^" + QRegExp::escape(textToFind) + ".+"));
}
int index = indexOfLineStartingWith(stringList, "bnd|gf");  //it's not needed to escape characters here

首先,实际数据从第4行开始(不包括标题)。第二,每个数据字符串都有特定的布局,您可以对其进行解析。假设您将整个文件读取到QStringList中,其中列表中的每个项目代表每一行,则可以执行以下操作:

QStringList data;
[..]
for (int i = 3; i < data.size(); i++) {
    const QString &line = data.at(i);
    // Parse the X1 and X2 columns' values
    QString strX1 = line.section('|', 1, 1, QString::SectionSkipEmpty).trimmed();
    QString strX2 = line.section('|', 2, 2, QString::SectionSkipEmpty).trimmed();
}