views:

27

answers:

1

I was programming a small notepad like app with some extra functionalities.

I am using a rich textbox as the main area. My question is while performing operations on the contents of the textbox, like code formatting, highlighting, etc which might require reading each character and replacing wherever necessary. Moving back across text indexes occasionally. What would be more efficient for an autoformat button:

  • Directly reading on the textbox.text property. Appending the formated string chars into a stringbuilder & finally back to the textbox (using toString function).

    or

  • Copying the entire content into a string, reading character by character into a new stringbuilder.....and as above. Doesn't this method create an extra copy of the big text content in the textbox? Or is it more efficient than accessing the textbox control repeatedly?

Also if possible some ideas on keeping track of functions, brackets, braces, etc (for on-the-fly code formating) in the textbox code would be helpful.

A: 

Because you are going to have to parse the code for formatting, I would not do this from the textbox itself. I would copy the entire textbox contents into a string and read characters from the string. This is because interacting with any control adds another layer of complexity, as far as the program itself is concerned. Instead of accessing a String variable to get a character directly, you need to first access the Textbox control which then accesses it's internal representation of your text to get the character. It's an extra step and, for large amounts of text, it will slow your application down.

To do the actual parsing and formatting, you can either write your own tokenizer and formatter or use one that's already been built. I can't offer much help on either, but unfortunately it's not as simple as just tracking braces. Take a look at Sourceforge or similar sites; they might have formatters that you can study to help you build your own.

SimpleCoder
Thank you for the reply. I guess the main issue is solved. Regarding the on-the-fly formating, I understand it is not as easy to create a formatter but the job I am looking to be done is simply to keep the braces tabbed in a neat way, nothing big like what an IDE does.
loxxy
That's definitely easier, however you still need to make sure the brace you are balancing is not in a string literal (like "(").
SimpleCoder