LebGeeks

A community for technology geeks in Lebanon.

You are not logged in.

#1 December 17 2011

Joe
Member

[Exercise] Tab and space

This exercise is taken from the K&R, but feel free to use any language you want.

Exercise 1-20. Write a program detab that replaces tabs in the input with the proper number
of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every 4 columns.

Offline

#2 December 17 2011

Joe
Member

Re: [Exercise] Tab and space

My code in C

#include <stdio.h>
#include <stdlib.h>

const int TAB_STOP = 4;

char *s = "Some list\tto work\ton\t.";
int detab (int i); 

int main (int argc, char **argv)
{
    int i = 1;
    char *ptr = NULL;

    for (ptr=s; *ptr != '\0'; ++ptr)
        if (*ptr == '\t')
            i = detab(i);
        else {
            printf("%c", *ptr);
            i++;
        }   
    return EXIT_SUCCESS;
}

int detab (int i)
{
    printf(" ");
    i++;

    return i % TAB_STOP == 0 ? i: detab (i);
}

Offline

#3 December 17 2011

Zef
Member

Re: [Exercise] Tab and space

I did one in Ruby. It works via the command line and you can detab the a list of files that you pass as arguments. You can also specify the tabstops, but by default I used two since I'm partial to that :)


# This would detab the file itself and another file
ruby detab.rb detab.rb /some/other/file.rb
# This would use 4 spaces instead of two
ruby detab.rb --tabstop=4 detab.rb /some/other/file.rb

And the code itself:

if match = ARGV.first.match(/--tabstop=(\d)/)
  ARGV.delete_at 0
  tabstop = match[1].to_i
else
  tabstop = 2
end

SPACES = ' ' * tabstop

def detab(text)
  text.gsub(/\t/, SPACES)
end

files = ARGV

for path in files
  begin
    content = File.read(path)
    File.open(path, 'w') do |file|
      file.write detab(content)
    end
  rescue
    puts "Could not edit file: #{path}"
  end
end

Last edited by Zef (December 17 2011)

Offline

#4 December 17 2011

Joe
Member

Re: [Exercise] Tab and space

@zef: great to see you!

There's a small problem with your code. It assumes that a TAB is always TABSTOP * ' ', which is not always the case. It depends on the position of your cursor.

Say tabstop is 4 (for clarity. It is also valid for 2, 3 or one bazillion).

If your cursor is at position 7 and you press tab, you don't go to p11. you go to p8. Or the next valid tabstop.
If your cursor is at position 5 you also get to p8.

Offline

Board footer