Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi,
i read a text file and i want to add multiple strings to the line i'm reading.
let s say for exemple : i read a text file, i want to had "m " and "ing"
the new line will be : i m reading a text file.
i m using stringbuilder.insert.

Insert(Int32, String, Int32) Inserts one or more copies of a specified string into this instance at the specified character position.

i create an objet : with the position, the string i want to had, and the number of time i want to repeat it.
here is part of my code:

C#
StreamReader sr = new StreamReader(line);
StreamWriter sw = new StreamWriter();


                  while (!sr.EndOfStream)

                {

                    string line = sr.ReadLine();

                    StringBuilder sb= new StringBuilder(line);

                    foreach(fields field in listfield)
                    {

           sb.Insert(field.position,field.string, field.numberOftime);
// so for the "m"          sb.insert(3,"m_",1)
// so for the "ing"        sb.insert(7,"ing",1)
                    }
 sw.WriteLine(builder.ToString());


the problem is that the index changes. For the "ing" will be sb.insert(9,'ing',1) and not (7,"ing",1) and it's normal, but for the user: he only want to add in (7,"ing,1").
Any idea of how can i do it ?
Thx for your help
Posted

1 solution

Two options that come to mind:

  1. Perform the inserts in reverse order. This ensures that the index at which to insert does not change for all subsequent inserts.
  2. Keep record of the total length of strings already inserted, and add that to the index with each insert. In other words, "m_" is two characters long, so when inserting "ing", insert it as (7+2,"ing",1).
 
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