在Qt中查找文件中的特定字符
如何在QFile中找到包含文本的特定字符 例如,我在文件的某个地方写了“5000美元”。我想找到“$”符号,这样我就会意识到我已经达到了这个数字 我尝试使用QString QTextStream::read(qint64 maxlen),将1作为maxlen:在Qt中查找文件中的特定字符,qt,Qt,如何在QFile中找到包含文本的特定字符 例如,我在文件的某个地方写了“5000美元”。我想找到“$”符号,这样我就会意识到我已经达到了这个数字 我尝试使用QString QTextStream::read(qint64 maxlen),将1作为maxlen: QFile myfile("myfile.txt"); myfile.open(QIODevice::ReadWrite | QIODevice::Text); QTextStream myfile_stream(&myfile
QFile myfile("myfile.txt");
myfile.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream myfile_stream(&myfile);
while(! myfile_stream.atEnd())
{
if( myfile_stream.read(1) == '$')
{
qDebug()<<"found";
break;
}
}
QFile-myfile(“myfile.txt”);
打开(QIODevice::ReadWrite | QIODevice::Text);
QTextStream myfile_流(&myfile);
而(!myfile_stream.atEnd())
{
如果(myfile_stream.read(1)='$')
{
qDebug()您发布的错误消息与代码中的问题不匹配。该错误可能是由其他原因引起的
QTextStream::read
返回QString
。您不能直接比较QString
和const char*
,但是操作符[]
可以帮助:
QString s = stream.read(1);
if (s.count() == 1) {
if (s[0] == '$') {
//...
}
}
但是,用太小的片段读取文件会非常慢。如果文件足够小,您可以一次读取所有文件:
QString s = stream.readAll();
int index = s.indexOf('$');
如果您的文件很大,最好按小块(例如1024字节)读取文件,并使用indexOf
结果和已读取的块数计算找到的字符的索引。一次读取一行,然后搜索已读取的文本
QTextStream stream(&myFile);
QString line;
do
{
line = stream.readLine();
if(line.contains("$"))
{
qDebug()<<"found";
break;
}
} while (!line.isNull());
QTextStream流(&myFile);
QString线;
做
{
line=stream.readLine();
如果(第行包含($))
{
qDebug()可以使用
QTextStream myfile_stream(&myfile);
QChar c;
while (!myfile_stream.atEnd())
myfile_stream >> c;
if (c == '$') {
...
}
myfile\u stream.read(1)
-这不是一种好的做法,您不应该一次读取一个字节的文件。请读取整个文件,或者如果存在文件太大而无法放入内存的风险,请逐行进行缓冲
您得到的错误是因为您将QString
与字符文本进行了相等性比较-不用说,这不会像预期的那样起作用。即使字符串中只有一个字符,字符串也是字符串。建议您使用[]
运算符或更好的方法读取-QString::at()const
保证不会创建额外副本。您不会在QFile
上使用它,也不会在QTextStream
上使用它,而是在从针对该文件的文本流的read()
方法返回的QString
上使用它
在内存中存储文本后,可以使用常规的QString
方法,如indexOf()
来搜索包含字符的索引
我想找到“$”符号,这样我就会意识到我已经到达了终点
号码
在我看来,您搜索“$”符号是因为您对它后面的美元值更感兴趣。在这种情况下,我建议逐行读取文件并通过QRegExp
运行它们,以提取您要查找的任何值
QRegExp dollarFind("\\$(\\d+)");
while(!myfile_stream.atEnd()){
QString line = myfile_stream.readLine();
if (dollarFind.exactMatch(line)){
QStringList dollars = dollarFind.capturedTexts();
qDebug() << "Dollar values found: " << dollars.join(", ");
}
}
QRegExp dollarFind(\\$(\\d+);
而(!myfile_stream.atEnd()){
QString line=myfile_stream.readLine();
if(dollarFind.exactMatch(行)){
QStringList$s=dollarFind.capturedTexts();
qDebug()