I'm a little stumped on a section of code in my program. I'm trying to take in a string of chars and then store each word within that string separately in an array of strings without using stdtok and then output them with only a single space separating each word, even if the two words were originally separated by more than one space in the input.. I have most of the code but I can't figure out how to how to load the string array after I add a null char after each word. Having a brain fart... Please help.

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

int main (void) 
{
   int i, j=0, count=0, length=0;
   char array_char[1023];
   char* array_str[512];	
	
   fputs("Type a string of words and then press 'Enter': ", stdout);
   fflush(stdout); 
   fgets(array_char, sizeof array_char, stdin);
	
   length = strlen(array_char);   // add (-1) to delete the newline
	
   printf(array_char);
   printf("\n");
	
   for(i=0; i<length; i++)
   {
	if(array_char[i] == ' ')
	{
	   array_char[i] = '\0';
	   do
	   {
		i++;
	   }
	   while(array_char[i] == ' ');
	}
	else
	{
	   continue;
	}
   }
	
	
   //add code here (without using stdtok) that loads each word in the string (until it encounters a null) into an array of strings.
   //increment 'count' each time
	
	
   for (i = count; i >= 0; i--) //yes I'm outputting them in reverse on purpose
   {
      printf("%s ", array_str[i]);
   }
      printf("\n");
	
   return 0;
}

You can do it all in the first for loop. All you need to do is save the start of a word in the array_str like array_str[j++] = &array_char[i]; and insert the '\0' as you are doing.

Here is a way to get rid the '\n'.

#include<stdio.h>
#include<string.h>
int main (void)
{
   int i, j=0,
       count=0, length=0,
       inWord=0;
   char array_char[1023];
   char* array_str[512];
   char *tmp;

   fputs("Type a string of words and then press 'Enter': ", stdout);
   fflush(stdout);
   fgets(array_char, sizeof array_char, stdin);
   // Get rid of the '\n' if there
   if ( (tmp = strchr(array_char,'\n') )){
      *tmp = '\0';
   }
   length = strlen(array_char);   // Now the newline is gone

   printf("%s\n",array_char);

Thank you. In the end I went a slightly different way but reading and playing around with your reply helped me to finally understand it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.