Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- avp 2014 str_locword()
- little function to locate word in char[] string
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- // Returns start of n'th word in str[] and it's length (in *wlen)
- // or pointer to end of string and length == 0
- char *str_locword (const char *str, int nword, int *wlen);
- static inline int
- skipword (const char *w)
- {
- int l = 0;
- while (w[l] && !isspace(w[l++]));
- return w[l] ? --l : l;
- }
- char *
- str_locword (const char *str, int nword, int *wlen)
- {
- *wlen = 0;
- do {
- str += *wlen;
- while (isspace(*str))
- str++;
- *wlen = skipword(str);
- } while (*wlen && nword--);
- return (char *)str;
- }
- #if TEST
- #define FGETS(prompt,str,size,file) \
- (fputs((prompt), stdout), fflush(stdout), \
- fgets((str), (size), file))
- int
- main (int ac, char *av[])
- {
- char str[1000];
- while (FGETS("Enter str: ", str, 1000, stdin)) {
- str[strlen(str) - 1] = 0;
- int wsz, nw;
- char *w;
- if (sscanf(str, "%d", &nw) == 1) {
- printf ("word %d :", nw);
- w = str_locword(str, nw, &wsz);
- char word[wsz + 1];
- strncpy(word, w, wsz);
- word[wsz] = 0;
- printf (" [%s]\n", word);
- }
- }
- return puts("\nend") == EOF;
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement