Skip to content

Instantly share code, notes, and snippets.

@rajaravivarma-r
Created August 21, 2019 11:22
Show Gist options
  • Select an option

  • Save rajaravivarma-r/8e0c037a6ff351f670d0324021983a8d to your computer and use it in GitHub Desktop.

Select an option

Save rajaravivarma-r/8e0c037a6ff351f670d0324021983a8d to your computer and use it in GitHub Desktop.
Qt code to split string into parts, into parts of a particular length
#include <QDebug>
#include <QString>
#include <QStringList>
#include <QRegularExpression>
#include <QRegularExpressionMatchIterator>
#include <QFile>
class StringSplit {
public:
StringSplit(QString string) {
this->mString = string;
}
// Splits the string into <number> of parts
QStringList intoParts(int number) {
QStringList list;
QString temporaryString{""};
unsigned int stringSize = this->mString.size();
for(unsigned int i = 0; i <= stringSize; ++i) {
temporaryString += this->mString[i];
if (temporaryString.size() == number || i == stringSize) {
list << temporaryString;
temporaryString.clear();
}
}
return list;
}
// Splits the string into parts with <number> of characters
QStringList intoPartsOfLength(int number) {
QRegularExpression re(
QString(R"((.{0,%1}))").arg(number),
QRegularExpression::MultilineOption | QRegularExpression::DotMatchesEverythingOption
);
QRegularExpressionMatchIterator i = re.globalMatch(this->mString);
QStringList list;
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
QString word = match.captured(1);
if (word.size() > 0)
list << word;
}
return list;
}
private:
QString mString;
};
QString fileContents(const QString &filename) {
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return QString();
return QString(file.readAll());
}
int main(int argc, char** argv) {
auto contents = fileContents("/Users/rajaravivarma/Github/qt-split-string/orange_story");
StringSplit ss{contents};
qDebug() << "From intoPartsOfLength List";
for(const auto &s : ss.intoPartsOfLength(100)) {
qDebug() << "\n\n";
qDebug().noquote() << s;
qDebug() << "\n\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment