My daily text editing question....

I'm traversing a text file line by line adjusting the text so that the file eventually will match the syntax required to be run on a MIPS simulator (MARS). My issue is that whenever I see a line with the string "blezl" in it, I want to do several things. First I need to insert some lines of text following the line containing this word. That's easy enough using insert. I then have to insert some lines of text after the line that originally followed the found line. The problem is, I need to then search the entire document for a string that was at the end of the found string and then insert a few lines before any lines that contain the 2nd string found. So..

#1  blezl v0,#10
#2  addu  s1,s0,s5
#3  lw    v1,0(s8)
...
#10 addu  s1,s0,s5

i need to find "blezl", and then I insert some lines between "#1" and "#2". Then I insert some lines between "#2" and "#3", and then I need to search the entire document for "#10" and when I find any, I insert some lines before it. The problem is that the last step requires that I search the entire document (in the middle of traversing line by line until blezl was found). This is because "#10" could occur anywhere before or after "#1". This is going to take forever (there are 80k lines in my file and probably about 2% of them have "blezl" in them.) How can I do this without the massive redundant step?

If the #1, #2, etc. strings are unique and recognizable without knowing whether they're needed, then just make a single preliminary pass through the file, finding all such strings, and putting them into a map that leads to their locations.

Then, each time you want to locate such a string, just look it up in the map.

If you store all your lines in a list, you can use a map that maps the number in front of each line to its iterator in the list.
That way you can both find the line in question very quickly and any line insertions will be very cheap.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.