K&R answer book exercise 1.21

前端 未结 2 840
广开言路
广开言路 2021-01-24 01:08

Here is the question:

Write the program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use th

2条回答
  •  花落未央
    2021-01-24 01:49

    It does not have a name or something like that.
    In detail:

    First of all, how much pos has to be increased depends on pos%TABINC,
    ie. TABINC is 8, so if pos is a multiple from 8, add 8,
    if pos%8 is 1 (like 9, 17...) then add 7,
    if pos%8 is 2 (10, 18...) add 6 and so on.

    Full list:
    pos%8 -> number to add
    0 -> 8
    1 -> 7
    2 -> 6
    3 -> 5
    4 -> 4
    5 -> 3
    6 -> 2
    7 -> 1

    That would be 8 - pos%8 or, more general TABINC - pos%TABINC

    Important: A negative number modulo something in C is mathematically not correct
    In C, for a,b >= 0: (-a)%b == -(a%b)

    What is added in the code is (TABINC - (pos - 1) % TABINC) - 1
    With some basic math and the fact above, this is
    (TABINC - (pos - 1) % TABINC) - 1
    = TABINC - ((pos - 1) % TABINC)) - 1
    = TABINC - ((pos % TABINC) - 1) - 1
    = TABINC + 1 - (pos % TABINC) - 1
    = TABINC - (pos % TABINC)
    which is the same as my short formula above, only more complex for no reason.

提交回复
热议问题