Created
June 4, 2012 09:16
-
-
Save joehakimrahme/2867392 to your computer and use it in GitHub Desktop.
K&R (1.21): Replace blanks by tabs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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