Skip to content

Instantly share code, notes, and snippets.

@sqroot3
Last active May 10, 2018 23:41
Show Gist options
  • Save sqroot3/f14914ccb6c4fa7f58b6b50928422074 to your computer and use it in GitHub Desktop.
Save sqroot3/f14914ccb6c4fa7f58b6b50928422074 to your computer and use it in GitHub Desktop.
linefold.c - program that folds long input lines into shorter lines after first nonwhitespace character
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// Write a program to fold long input lines into 2 shorter lines
// after first nonblank character. Take care of very long lines,
// and if there's no blanks/tabs before column
// Essentially a string tokenizer
int length(char input[]);
int main(int argc, char* argv[])
{
if(argc < 3)
{
printf("Usage: %s input [n]\n", argv[0]);
exit(1);
}
int COL_BOUND = atof(argv[2]);
int startCol, currentCut, nextBound, numOfCuts;
startCol = currentCut = nextBound = numOfCuts = 0;
//while the next bound is still "inside" string
while((nextBound = startCol + COL_BOUND - 1) <= length(argv[1]))
{
//find cut character
for(int i = startCol; i <= nextBound; ++i)
{
if(isspace(argv[1][i]) && !isspace(argv[1][i-1]))
currentCut = i - 1;
}
//there was no valid "cut" before whitespace or bound itself is valid
if(!isspace(argv[1][nextBound]) || currentCut <= startCol)
currentCut = nextBound;
//print [startCol, cut]
int printed = 0;
for(int i = startCol; i <= currentCut; ++i)
{
if(isspace(argv[1][i]) && printed == 0)
continue;
++printed;
putchar(argv[1][i]);
}
printf("\n");
//adjust start column for the next run
startCol = startCol + COL_BOUND;
++numOfCuts;
}
//print remaining characters
int printed = 0;
++numOfCuts;
for(int i=startCol; i <= length(argv[1]); ++i)
{
if(isspace(argv[1][i]) && printed == 0)
continue;
++printed;
putchar(argv[1][i]);
}
printf("\nOriginal string split into %d parts (bound was %d)\n", numOfCuts, COL_BOUND);
return 0;
}
int length(char input[])
{
int i;
for(i=0; input[i] != '\0'; ++i)
;
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment