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]
CodePudding user response:
A solution would be to just .removeLast() on the list that you split.
String text = 'Test1\nTest2\nTest3\nTest4';
List<String> list = text.split('\n');
text = list.removeLast();
print(list); // [Test1, Test2, Test3]
print(text); // Test4
CodePudding user response:
To me you are combining two questions. Every language I know has built-in ways to split a string on a char, including newline chars. The distinct thing you want is a split function that doesn't include the last entry.
You may be combining your answers as well :) Is there some resource constraint or streamed input that prevents you from just building the list, then popping off the final entry?
If yes: I think you have to build your own split. Look at the implementation code for LineSplitter(), and make something similar except which leaves the final entry.
If no: simply call
MyString = MyList.removeLast();
after your for-loop.
