Home > Blockchain >  How to split a string based on empty/blank lines?
How to split a string based on empty/blank lines?

Time:11-05

I'm writing a c application (Qt Widgets) that is supposed to parse an .srt subtitle file. Each part of the file is separated by an empty line, like this:

1
00:00:08,000 --> 00:00:11,000
[Line]

2
00:00:56,034 --> 00:00:57,492
[Line]
[Another line]

3
00:01:13,676 --> 00:01:15,420
[Line]

Basically, I want to read the entire file to a QString, and split it by empty lines into QString array, each item containing one of those sections like this:

2
00:00:56,034 --> 00:00:57,492
[Line]
[Another line]

However, I cannot figure out how to do this. I tried splitting the string by \r and \n, but that split everything into separate lines, not by empty lines.

This is the routine I had in mind to get the data from the .srt file:

  • Read all of the contents of the file to a QString (named something along the lines of content).
  • Split the QString by empty lines, and append to a QStringList (named something along the lines of sections).
  • For each item in sections, split the second line by the --> identifier, and assign indexes 0 and 1 to QString variables called startTime, and endTime, respectively.
  • Take the rest of the lines (everything after line 2 is the subtitle text), and append them to a QString called subtitleText.
  • Add all the gathered information to an SrtSubtitle instance, and append it to QList<SrtSubtitle>

How can I achieve this?

CodePudding user response:

when reading text files, newlines are usually represented as \n

With this you can split your string using \n\n

this will split it when it is 2 new lines without anything between them.

  • Related