Something like this should work:
string newGPA = " newgpa";
string myLine = "first \t last \t oldgpa";
int lastTabIndex = myLine.LastIndexOf("\t");
string oldGPA = myLine.Substring(lastTabIndex + 1);
myLine = myLine.Replace(oldGPA, newGPA);
Where "myLine" would be the line that identifies the 5th student for example.
All this code does is to get the index of the last tab in the string, then get the old gpa from the string as a substring, and finally replace it with the new gpa.
Hope this makes sense.
michelleradu
Junior Poster in Training
55 posts since Dec 2009
Reputation Points: 10
Solved Threads: 5
Skill Endorsements: 0
I would suggest you to create a new class name it "Student", add some properties like Firstname, lastname and gpa.
Create a genertic list<T> where T will be class name:
List<Student> listOfStudents = new List<Student>();
Now loop through the rows on the text file, on each row split data (by "\t") this way you will get 3 indexes:
data[0] will be firsname
data[1] will be lastname and
data[2] will be gpa.
Create a new Student and fill these data to properties and add a reference of a student to a list:
Student s = new Student();
s.Firstname = data[0];
s.Lastame = data[1];
s.Gpa = data[2];
listOfStudents.Add(s);
As said, All this must be done in a loop while reading file (you can use StreamReader class and while loop):
List<Student> listOfStudents = new List<Student>();
StreamReader sr = new StreamReader(@"FullFilePath");
string line;
while((line = sr.ReadLine()) != null)
{
string[] data 0 line.Split(new string[]{"\t"}, StringSplitOptions.RemoveEmptyEntries);
if(data.Length == 3) //check if there are really 3 types of data
{
Student s = new Student();
s.Firstname = data[0];
s.Lastame = data[1];
s.Gpa = data[2];
listOfStudents.Add(s);
}
}
Now you have a list of all students, and you can simply add the one you need.
For example if you wanna edit the 5th one you can just specify the index of listOfStudents:
listOfStudents[4].Gpa = "new gpa";
This is about it.
And not to forget, now you have to do the reverse and write the data from the list back to file (simple overwrite all the data in file - actually like you would create a new file - use StreamWriter class.
Mitja Bonca
Posting Maven
2,561 posts since May 2009
Reputation Points: 642
Solved Threads: 486
Skill Endorsements: 13