setevoy
setevoy

Reputation: 4662

Print one word from string

I want to print for example third word from some string.

In example below - it works, but - can it be made other, better, way?

#include <stdio.h>
#include <string.h>

char str1[20] = "This is string";
int a, b = 0, nums = 1;
char sec[20];

int main()
{
    for (a = 0; a <= strlen(str1); a++) {

        if ( str1[a] != ' ')
        {
            printf ("%c", str1[a]);

           if (nums == 3)
            {
                sec[b] = str1[a];
                ++b;
            }

        } else {
            printf ("\n");
            ++nums;
        }
    }

    printf ("\n\n%s\n", str1);
    printf ("Total words count: %d\n", nums);

    printf("Third word: %s\n", sec);

    return 0;

}

May be - with *pointers, instead of arrays[], or something else?

Also - is it good idea to use nested if operators in C?

Upvotes: 0

Views: 1045

Answers (2)

chux
chux

Reputation: 153368

Use "%n to locate the ends of the sub-string being sought.

No modifications or copying of the source string are needed.

void Print_Nth_word(const char *s, unsigned n) {
  if (n > 0) {
    int left;
    int right;
    while (1) {
      left = right = 0;
      sscanf(s, " %n%*s%n", &left, &right);
      if (right <= left) return;  // no sub-string (word) found
      if (--n == 0) break;
      s += right;
    }
    printf("%.*s\n", right - left, &s[left]);
  }
}

" %n%*s%n" detail:
" " Skip white space.
"%n" Save offset of current scanning.
"*s" Scan, but do not save non-whitespace. (a word)

"%.*s", right - left, &s[left] detail: Print &s[left] up to right - left characters.

Upvotes: 1

Fjotten
Fjotten

Reputation: 357

Maybe this is not the most elegant solution, but you could use strtok(). Assuming that all your words are separated by spaces, then it is just a matter of strtok'ing x number of times. I just threw this thing together real quick, but it should work OK, I hope.

#include <string.h>
#include <stdio.h>

int main( void ) {
    char str[] = "This is a string\n";
    char *token;
    int i;
    token = strtok( str, " ");
    i = 1;
    while( token != NULL ) {
        if( 3 == i ) {
            fprintf( stdout, "%s\n", token );
            fflush( stdout );
        }
        token = strtok(NULL, " ");
        i++;  // <-- this was missing
    }
    return 0;
}

Upvotes: 4

Related Questions