Joseph .M 101
Joseph .M 101

Reputation: 221

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

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:

How can I achieve this?

Upvotes: 1

Views: 1218

Answers (2)

I would improve upon ziarra's answer. You certainly want the solution to be robust and work also with Windows line endings which are "\r\n" instead of "\n". In that case ziarra's solution would not suffice.

So my proposal is to do it in two steps:

  1. replace all occurrences of "\r\n" with "\n"
  2. split the text by "\n\n" (as ziarra suggests)

Upvotes: 1

ziarra
ziarra

Reputation: 137

New lines are usually represented as \n.

To split the string when there are 2 new lines without anything between them, you can use \n\n as delimiter.

Upvotes: 3

Related Questions