c++ 使用 .indexOf 在 QStringList 中查找以 "..." 开头的文本
c++ find text in QStringList that starts with "..." using .indexOf
我有一个关于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();
}
相关文章:
- 文本文件中的单词链表
- 从命令行c++发送文本文件名
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 当文本以分量计开头时,将文本C++到 std::vector 中
- 以 LPCTSTR 开头编写另一行文本的最佳方法是什么?
- 如何检查包含 utf8 文本的 std::string 在 Windows 中是否以大写字母开头?
- Qt C++ 如何在文本编辑的开头获取光标
- 在每行的开头和结尾添加文本
- 这是怎麽?在读取使用 Unicode 编码的文本文件后控制台输出的开头
- 在c++中写入文本文件的开头
- c++ 使用 .indexOf 在 QStringList 中查找以 "..." 开头的文本
- 如何检查文本文件中的特定行是否以特定单词开头
- 从文本文件开头的行中删除空格