Over a million developers have joined DZone.

Dealing With Off by x Issues When Using the TextBox


One of the toughest problems I faced when I built Notepad Classic was an issue where many functions like Go To & Find were always off a few characters. After a bit of experimenting I noticed a pattern, it was off by the number of characters equal to the line number (0 based).

i.e.: no issues on the first line (line index 0); Off by one on the second line (line index 1); Off by two on the third line (line index 2); Off by three on the forth line etc…


It turned out that the way the string functions count a line break (i.e. \r\n) as two characters, and rightly so – it is two characters a \r & a \n. However the TextBox functions like Select treat \r\n as a single character because that is what is displayed visually – a line break is one character visually. So there is a difference between the two scenarios and thus the “off by one x line count” error I found.


The solution I used is to compensate for it by working out the number of lines to the point (i.e. count all the line breaks before the point) and adjusting the results (adding +1 for each \r\n) as needed.

Sample application to show this problem and the solution can be found at: https://bitbucket.org/rmaclean/off-by-one-line-sample-code/src


Published at DZone with permission of Robert Maclean , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}