Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am reading a text file using streamreader.

I want to split the text of file into string of arrays or any collection.

e.g.

Student: Prasad,
xyz
abc
some text here about Prasad.
Student: Raj
abc
ijk
some text here about Raj
Student: Shaan
xxx
some text here about Shaan

Now...

I want the string array as below

C#
array[0] ="Student: Prasad,
xyz
abc
some text here about Prasad."

array[1] ="Student: Raj
abc
ijk
some text here about Raj"

array[2]="Student: Shaan
xxx
some text here about Shaan
"
Posted
Comments
Prasad Avunoori 25-Feb-15 6:09am    
In above e.g. Student: is my keyword.
[no name] 25-Feb-15 6:14am    
take a look at String.Split(..)
Prasad Avunoori 25-Feb-15 6:17am    
That didn't work..
[no name] 25-Feb-15 6:19am    
Why not?
Richard MacCutchan 25-Feb-15 6:29am    
Each time the input text contains the keyword, you add a new entry to your array, and then fill it with the following lines of text. If you show the code you have tried and explain what does not work, then we can try to help you.

1 solution

Either use String.Split:
C#
string inp = File.ReadAllText(@"D:\Temp\xxx.txt");
string[] sections = inp.Split(new string[] {"Student: "},StringSplitOptions.RemoveEmptyEntries);
Or a regex:
C#
string inp = File.ReadAllText(@"D:\Temp\xxx.txt");
string[] sections = Regex.Split(inp, "Student: ",);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900