How many spaces for tab character(\t)?

前端 未结 3 513
粉色の甜心
粉色の甜心 2020-12-05 05:02

I want to implement a text drawing function. But I am not sure how \\t works, which means I don\'t know how many spaces I should print for \\t.

3条回答
  •  广开言路
    2020-12-05 06:00

    Imagine a ruler with tab stops every 8 spaces. A tab character will align text to the next tab stop.

                                    0       8       16      24      32      40
                                    |.......|.......|.......|.......|.......|
    printf("\tbar\n");              \t      bar
    printf("foo\tbar\n");           foo\t   bar
    printf("longerfoo\tbar");       longerfoo\t     bar
    

    To calculate where the next tab stop is, take the current column.

    nextTabStop = (column + 8) / 8 * 8
    

    The / 8 * 8 part effectively truncates the result to the nearest multiple of 8. For example, if you're at column 11, then (11 + 8) is 19 and 19 / 8 is 2, and 2 * 8 is 16. So the next tab stop from column 11 is at column 16.

    In a text editor you may configure tab stops to smaller intervals, like every 4 spaces. If you're simulating what tabs look like at a terminal you should stick with 8 spaces per tab.

提交回复
热议问题