Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to build a list from a carriage return separated string?

Background

I have the following string:

var MyString = 'Test1⏎Test2⏎Test3⏎Test4'

= line feed = \n

What I’m trying to do

  • I want to create a List which is a list of lines. Basically every item that is followed by a \n would become an entry in the list.
  • I want the base string MyString to become shortened to reflect what pieces of the string have been moved to the List
  • The reason I want to leave a residual MyString is that new data might come in later that might be considered part of the same line, so I do not want to commit the data to the List until there is a carriage return seen

What the result of all this would be

So in my above example, only Test1 Test2 Test3 are followed by \n but not Test4

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output List would be: [Test1, Test2, Test3]

MyString would become: Test4

What I’ve tried and failed with

I tried using LineSplitter but it seems to want to take Test4 as a separate entry as well

final lines = const LineSplitter().convert(MyString);
for (final daLine in lines) {
  MyList.add(daLine);
}

And it creates [Test1, Test2, Test3, Test4]

>Solution :

A solution would be to use .substring(...) to return everything before the last \n and then split it. After that you would just need to set the variable back to everything after the last \n.

String text = 'Test1\nTest2\nTest3\nTest4';

List<String> list = text.substring(0, text.lastIndexOf('\n')).split('\n');
text = text.substring(text.lastIndexOf('\n') + 1);

print(list); // [Test1, Test2, Test3]
print(text); // Test4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading