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
Listwhich is a list of lines. Basically every item that is followed by a\nwould become an entry in the list. - I want the base string
MyStringto become shortened to reflect what pieces of the string have been moved to theList - The reason I want to leave a residual
MyStringis 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 theListuntil 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
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