Data structure for text editor

后端 未结 5 1559
误落风尘
误落风尘 2021-01-29 20:41

This is an interview question. What data structure would you use to store the text in a text editor?

5条回答
  •  有刺的猬
    2021-01-29 20:52

    On good old ZX-Spectrum one (or more, I do not know) text exditor used very simple structure.

    There was one big buffer, which occupied all free RAM. Text was split in two parts at the cursor. Part before the cursor, was placed at the beginning of the buffer, and the rest at the end of the buffer. As text typed, data simply added to the end of first part, and when cursor is moved, text is copied forth and back.

    Buffer layout:

    Hello, World!
            ^------Cursor here
    
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |H|e|l|l|o|,| |W|   |o|r|l|d|!|
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |                ^         ^        |
    begin           cur1      cur2    end
    

    That's, how some edit operations was made:

    Type a char:    buffer[cur1++] = character
    
    Backspace:      cur1--
    
    Cursor left:    buffer[--cur2] = buffer[--cur1]
    
    Cursor right:   buffer[cur1++] = buffer[cur2++]
    

    Buffer in action:

                 Hello, W..............orld!
    Press right          ^             ^
                 Hello, Wo..............rld!
    Press backspace       ^             ^
                 Hello, W...............rld!
    Press 0              ^              ^
                 Hello, W0..............rld!
                          ^             ^
    

提交回复
热议问题