두 단어 사이의 공백의 수에 민감하지 않도록 qstring :: indexof 메소드를 지정하는 방법은 무엇입니까?
문제
나는 소스 코드를 작성했습니다 :
int main(int argc, char *argv[]) {
QFile File (directory + "/File");
if(File.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream Stream (&File);
QString FileText;
do
{
FileText = Stream.readLine();
QString s = "start";
QString e = "end here";
int start = FileText.indexOf(s, 0, Qt::CaseInsensitive);
int end = FileText.indexOf(e, Qt::CaseInsensitive);
if(start != -1){ // we found it
QString y = FileText.mid(start + s.length(), (end - (start + s.length())));
qDebug() << y << (start + s.length()) << (end - (start + s.length()));
}
.
}
내 문제는 int end= filetext.indexof (e, qt :: caseInsensitive);
"End"와 "여기"라는 단어 사이에 정확히 세 개의 공백이있을 때 QString e = "end here";
가 발견됩니다.이 텍스트 에서이 두 단어 사이의 공백을 읽은 텍스트에서는 분명히 시간과 시간이 다를 수 있기 때문에 이것은 문제입니다.또한 "End"와 "여기"두 단어를 모두 쓸 필요가 있습니다.나는 문제를 기초로 줄이고 누군가가 아이디어 / 해결책을 가지고 있기를 바란다.
해결책
QString::simplified()
메소드를 사용하여 공백 수를 1로 줄입니다..
다른 팁
또한 qregexp : 를 시도 할 수 있습니다.
#include <QDebug>
#include <QString>
#include <QRegExp>
int main()
{
QString text("start ABCDE1234?!-: end here foo bar");
// create regular expression
QRegExp rx("start\\s+(.+)\\s+end\\s+here", Qt::CaseInsensitive);
int pos=0;
// look for possible matches
while ((pos=rx.indexIn(text, pos)) != -1) {
qDebug() << rx.cap(1); // get first match in (.+)
pos+=rx.matchedLength();
}
return 0;
}
. 제휴하지 않습니다 StackOverflow