Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to filter(startWith()) ?



  • Filter lines startWith "#include";

    QStringList list = textEdit->toPlainText().split("\n");
    QStringList result;
    result = list.filter(list.at(i).startWith("#include"));
    


  • Hi @sonichy ,
    list.filter(list.at(i).startWith("#include")); is return bool value so it is not convert bool to QString type.

    this below is helpful to you,
    bool QString::startsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

    thank you.



  • @sonichy said in How to filter(startWith()) ?:

    Filter lines startWith "#include";

    QStringList list = textEdit->toPlainText().split("\n");
    QStringList result;
    result = list.filter(list.at(i).startWith("#include"));
    

    You can use a regular expression to find all strings starting with #include

    #include <QStringList>
    #include <QRegExp>
    
    ...
    
      QStringList result;
      result = list.filter(QRegExp("^#include.*"));
    
    ...
    

  • Qt Champions 2019

    @sonichy Use a regular expression:

    result = list.filter(QRegularExpression("^#include.*"));
    

  • Lifetime Qt Champion

    Hi,

    Please use QRegularExpression, QRegExp is to be considered deprecated with Qt 5.



  • Or if you are a parallel hipster:

    Using Qt:

    QStringList list = textEdit->toPlainText().split("\n");
    QStringList result = QtConcurrent::blockingFiltered(list , [](const QString& val)->bool{return val.startWith(QLatin1String("#include"));});
    

    using C++17:

    QStringList list = textEdit->toPlainText().split("\n");
    QStringList result;
    std::copy_if(std::execution::par,list.cbegin(), list.cend(), std::back_inserter(result), [](const QString& val)->bool{return val.startWith(QLatin1String("#include"));});
    

Log in to reply