[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 217
  • Last Modified:

How do i loop thru newlines that are in a string variable?

I have a string variable that has been populated with "contents = reader.ReadToEnd();". How can i create a for loop that goes thru each line in "contents", kind of like how ReadLine() works except it's working with the string variable, not the file itself?
0
bemara57
Asked:
bemara57
  • 2
1 Solution
 
JimBrandleyCommented:
The code below will read the lines.

Jim

private string GetNextLine(string input, int startPos)
{
   if (startPos >= input.Length)
      return string.Empty;
   int pos = input.IndexOf('\n', startPos);
   if (pos > -1)
      return input.Substring(startPos, pos - startPos);
   return input.Substring(startPos);
}
private void Test_Click(object sender, EventArgs e)
{
   string someLines = "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz";
   int startIndex = 0;
   string oneLine = GetNextLine(someLines, startIndex);
   while (oneLine.Length > 0)
   {
      // do something with the line
      startIndex += oneLine.Length + 1;
      oneLine = GetNextLine(someLines, startIndex);
   }
 }

Open in new window

0
 
JimBrandleyCommented:
If you want the newline returned with the line, use the code below.

Jim

private string GetNextLine(string input, int startPos)
{
   if (startPos >= input.Length)
      return string.Empty;
   int pos = input.IndexOf('\n', startPos);
   if (pos > -1)
      return input.Substring(startPos, pos - startPos + 1);
   return input.Substring(startPos);
}
private void Test_Click(object sender, EventArgs e)
{
   string someLines = "abc\ndef\nghi\njkl\nmno\npqr\nstu\nvwx\nyz";
   int startIndex = 0;
   string oneLine = GetNextLine(someLines, startIndex);
   while (oneLine.Length > 0)
   {
      // do something with the line
      startIndex += oneLine.Length;
      oneLine = GetNextLine(someLines, startIndex);
   }
 }

Open in new window

0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now