Skip to content

Instantly share code, notes, and snippets.

@joehakimrahme
Created June 4, 2012 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joehakimrahme/2867385 to your computer and use it in GitHub Desktop.
Save joehakimrahme/2867385 to your computer and use it in GitHub Desktop.
Entab: Replace blanks by tabs
#include <stdio.h>
#define TABSTP 4
/* TODO: read this string from argv,
to test different scenarios */
char* input_str = "Something to test it";
int nexttbstp (int position);
int printblank(int start, int end);
int main()
{
char *ptr = NULL;
int position = 1, blanknbr=0;
int c=0;
printf("%s\n", input_str);
for (ptr=input_str; *ptr != '\0'; ptr++) {
if (*ptr == ' ') {
blanknbr=0;
while (*ptr == ' ') {
blanknbr++;
ptr++;
}
if (printblank(position, position+blanknbr)) {
return -1;
}
position += blanknbr;
}
printf("%c", *ptr);
position++;
}
return 0;
}
/* Helper function that determines the next tabstop
from current position */
int nexttbstp (int position)
{
int relpos;
if (position <= 0)
return -1;
relpos = position % TABSTP;
return (position + (TABSTP - relpos));
}
int printblank(int start, int end)
{
int next, length;
if (end < start) {
printf("Error: end argument inferior to start\n");
return -1;
}
if ((next = nexttbstp (start)) == -1) {
printf("Error: negative position argument\n");
return -1;
}
/* Recursively insert as many tabs as possible,
then fill the rest with spaces */
if (end < next) {
length = end - start;
while (length--){
printf(" ");
}
return 0;
} else {
printf("\t");
return printblank(++next, end);
}
}
#include <stdio.h>
#define TABSTP 4
/* TODO: read this string from argv,
to test different scenarios */
char* input_str = "Something to test it";
int nexttbstp (int position);
int printblank(int start, int end);
int main()
{
char *ptr = NULL;
int position = 1, blanknbr=0;
int c=0;
printf("%s\n", input_str);
for (ptr=input_str; *ptr != '\0'; ptr++) {
if (*ptr == ' ') {
blanknbr=0;
while (*ptr == ' ') {
blanknbr++;
ptr++;
}
if (printblank(position, position+blanknbr)) {
return -1;
}
position += blanknbr;
}
printf("%c", *ptr);
position++;
}
return 0;
}
/* Helper function that determines the next tabstop
from current position */
int nexttbstp (int position)
{
int relpos;
if (position <= 0)
return -1;
relpos = position % TABSTP;
return (position + (TABSTP - relpos));
}
int printblank(int start, int end)
{
int next, length;
if (end < start) {
printf("Error: end argument inferior to start\n");
return -1;
}
if ((next = nexttbstp (start)) == -1) {
printf("Error: negative position argument\n");
return -1;
}
/* Recursively insert as many tabs as possible,
then fill the rest with spaces */
if (end < next) {
length = end - start;
while (length--){
printf(" ");
}
return 0;
} else {
printf("\t");
return printblank(++next, end);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment