Advertisement
Weegee

Untitled

Aug 28th, 2012
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. /* entab: Replaces strings of blanks by the corresponding number of tabs and
  2.    spaces */
  3. #include <stdio.h>
  4.  
  5. #define MAX_LENGTH 1000
  6.  
  7. int get_line(char line[]);
  8. void print_line(char line[], int line_length, int tab_length);
  9.  
  10. int
  11. main()
  12. {
  13.   char line[MAX_LENGTH];
  14.   int line_length;
  15.   int tab_length;
  16.  
  17.   tab_length = 8;
  18.   while ((line_length = get_line(line)) > 0)
  19.   {
  20.     printf("String with blanks:\n%s", line);
  21.     print_line(line, line_length, tab_length);
  22.   }
  23.   return 0;
  24. }
  25.  
  26. int
  27. get_line(char line[])
  28. {
  29.   int i;
  30.   char c;
  31.  
  32.   for (i = 0; i < MAX_LENGTH - 1 &&
  33.               (c = getchar()) != EOF &&
  34.               c != '\n'; i++)
  35.   {
  36.     line[i] = c;
  37.   }
  38.  
  39.   if (c == '\n')
  40.   {
  41.     line[i] = c;
  42.     i++;
  43.   }
  44.  
  45.   line[i] = '\0';
  46.   return i;
  47. }
  48.  
  49. void
  50. print_line(char line[], int line_length, int tab_length)
  51. {
  52.   int i;
  53.  
  54.   printf("String with tabs/blanks:\n");
  55.   for (i = 0; i < line_length; i++)
  56.   {
  57.     if (line[i] == ' ')
  58.     {
  59.       int j, blank_count;
  60.  
  61.       for (j = i; line[j] == ' '; j++);
  62.       if (j > i)
  63.       {
  64.         int k, tabs, spaces;
  65.  
  66.         blank_count = j - i;
  67.         tabs = blank_count / tab_length;
  68.         spaces = blank_count % tab_length;
  69.  
  70.         for (k = 0; k < tabs; k++, printf("\t"));
  71.         for (k = 0; k < spaces; k++, printf(" "));
  72.  
  73.         i = j - 1;
  74.       }
  75.       else
  76.       {
  77.         printf("%c", line[i]);
  78.       }
  79.     }
  80.     else
  81.     {
  82.       printf("%c", line[i]);
  83.     }
  84.   }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement