Advertisement
avp210159

str_locword

Jan 20th, 2014
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. /*
  2.   avp 2014 str_locword()
  3.  
  4.   little function to locate word in char[] string
  5. */
  6.  
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <ctype.h>
  12.  
  13. // Returns start of n'th word in str[] and it's length (in *wlen)
  14. //  or pointer to end of string and  length == 0
  15. char *str_locword (const char *str, int nword, int *wlen);
  16.  
  17. static inline int
  18. skipword (const char *w)
  19. {
  20.   int l = 0;
  21.   while (w[l] && !isspace(w[l++]));
  22.    
  23.   return w[l] ? --l : l;
  24. }
  25.  
  26.  
  27. char *
  28. str_locword (const char *str, int nword, int *wlen)
  29. {
  30.   *wlen = 0;
  31.   do {
  32.     str += *wlen;
  33.     while (isspace(*str))
  34.       str++;
  35.     *wlen = skipword(str);
  36.   } while (*wlen && nword--);
  37.  
  38.   return (char *)str;
  39. }
  40.  
  41. #if TEST
  42. #define FGETS(prompt,str,size,file)     \
  43.   (fputs((prompt), stdout), fflush(stdout), \
  44.    fgets((str), (size), file))
  45.  
  46. int
  47. main (int ac, char *av[])
  48. {
  49.   char str[1000];
  50.  
  51.   while (FGETS("Enter str: ", str, 1000, stdin)) {
  52.     str[strlen(str) - 1] = 0;
  53.     int wsz, nw;
  54.     char *w;
  55.     if (sscanf(str, "%d", &nw) == 1) {
  56.       printf ("word %d :", nw);
  57.       w = str_locword(str, nw, &wsz);
  58.       char word[wsz + 1];
  59.       strncpy(word, w, wsz);
  60.       word[wsz] = 0;
  61.       printf (" [%s]\n", word);
  62.     }
  63.   }
  64.  
  65.   return puts("\nend") == EOF;
  66. }
  67.  
  68. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement