What is wrong

This piece of code is not working as desired.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char str[]="This Sample Example", neww[100];
int i,j,k, counter=0;

for(i=0;str[i]!='\0';++i)
{
      if(str[i]==' ')
      {
	   if(counter==0)
	   {
                  for(k=0,j=i;str[j]!=' ';++k,++j)
		   neww[k]=str[j];
				
		   ++counter;
	    }
      }
}


I expect the variable neww to store the word "Sample". What is happening?
Thanks
for ( k=0, j=i+1; ...

str[i] is ' ' when you enter this for loop. If you set j to i, then str[j] is ' ' and the for loop's condition is false on the first iteration so the body of the loop is never executed. You should probably set neww[k] to '\0' when the outer loop is done.
Brilliant! Thanks a lot! :)
Topic archived. No new replies allowed.