Advertisement
ccmny

linecount

Sep 17th, 2011
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.98 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int linecount(char * string);
  6. char ** splitlines(char * string);
  7. void replacechar(char * string, char to, char with);
  8.  
  9. int main(int argc, char ** argv)
  10. {
  11.     char test[] = "Pierwsza linijka.\n Druga linijka.\n Trzecia linijka. \n";
  12.     char ** lines = splitlines(test);
  13.     while(**lines)
  14.         printf("%s\n", *lines++);
  15.     return 0;
  16. }
  17.  
  18. int linecount(char * string)
  19. {
  20.     int count = 0;
  21.     while(*string)
  22.         count += (*string++ == '\n');
  23.     return count;
  24. }
  25.  
  26. char ** splitlines(char * string)
  27. {
  28.     int lcount = linecount(string);
  29.     char ** lines = malloc((lcount + 1) * sizeof(char*));
  30.     int loffset = 0;
  31.     char * sptr = string;
  32.  
  33.     *(lines + loffset) = sptr;
  34.     loffset++;
  35.  
  36.     while(*sptr)
  37.     {
  38.         if(*sptr == '\n')
  39.         {
  40.             *(lines + loffset) = sptr + 1;
  41.             *sptr = '\0';
  42.             loffset++;
  43.         }
  44.         sptr++;
  45.     }
  46.     *(lines + loffset) = NULL;
  47.     return lines;
  48.  
  49. }
  50.  
  51. void replacechar(char * string, char to, char with)
  52. {
  53.     while(*string)
  54.     {
  55.         if(*string == to)
  56.             *string = with;
  57.         string++;
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement