What is a good way to loop through each line of a multiline string without using much more memory (for example without splitting it into an array)?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I suggest using a combination of
StringReaderand myLineReaderclass, which is part of MiscUtil but also available in this StackOverflow answer – you can easily copy just that class into your own utility project. You’d use it like this:Looping over all the lines in a body of string data (whether that’s a file or whatever) is so common that it shouldn’t require the calling code to be testing for null etc 🙂 Having said that, if you do want to do a manual loop, this is the form that I typically prefer over Fredrik’s:
This way you only have to test for nullity once, and you don’t have to think about a do/while loop either (which for some reason always takes me more effort to read than a straight while loop).