Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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;
- }
Add Comment
Please, Sign In to add comment