C examples for String:String Function
Fold long input lines into two or more shorter lines after the last non-blank character
#include <stdio.h> #define MAXLINE 1000/*from w ww .j a v a 2 s.c o m*/ #define TAB_WIDTH 8 #define LINE_WIDTH 10 void fold(char s1[], char s2[], int linewidth, int tabwidth); int main(void) { char s1[MAXLINE] = "this is a test. this is a test. this is a test. this is a test. this is a test. this is a test. this is a test."; char s2[MAXLINE]; fold(s1, s2, LINE_WIDTH, TAB_WIDTH); printf("\nfold result:\n%s\n", s2); return 0; } void fold(char s1[], char s2[], int lw, int tw){ int i= 0, l= 0, c, k = -1, w = 0; while ((c = s1[i]) != '\0') { if (c == ' ') { if (w + 1 == lw) { s2[l++] = '\n'; w = 0; i = k; } else { s2[l++] = ' '; ++w; } } else if (c == '\t') { if (w + tw - w % tw >= lw) { s2[l++] = '\n'; w = 0; i = k; } else { s2[l++] = '\t'; w += tw; } } else { s2[l++] = c; if (w + 1 == lw) { s2[l++] = '\n'; w = 0; } else { k = i; ++w; } } ++i; } s2[l++] = '\0'; }