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?