Reputation: 153
I have a string which contains a small code which is run dynamically. But i want to store each line of string in separate datastructure and also count the lines.
string CodeStr = @"using System";
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" Hello World");
}
}
}
For counting lines :
int count = 0;
int position = 0;
while ((position = CodeStr.IndexOf('\n', position)) != -1)
{
count++;
position++;
}
but i dont know how to get content at each line like
line 1 : using System;
line 2 : namespace ConsoleApplication2
line 3 : { and so on for the complete string.
Upvotes: 0
Views: 462
Reputation: 157048
Simply split the string using Split
if the string
is in code:
string[] lines = CodeStr.Split( new string[] { Environment.NewLine }
, StringSplitOptions.None
);
Or, if the file is read from disk, use File.ReadAllLines
:
string[] lines = File.ReadAllLines(yourFilePath);
Upvotes: 5