Flip words in a char array.
I am curious if I am on the right path of doing what I need to do. I appreciate the help.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[] = "Dog eat Cat";
char *b = NULL;
char *buffer = NULL;
int slen = 0, count = 0, templen = 0;
int size = strlen(a);
buffer = malloc((strlen(a)+1));
b = malloc((strlen(a)+1));
printf("First String: %s\n", a); /* Dog eat Cat */
buffer = strtok (a," ,.-");
while (buffer != NULL)
{
slen = strlen(buffer);
templen = slen;
while(buffer[count] != '\0')
{
b[size-(slen--)]=buffer[count++];
}
size = size-(templen+1);
count = 0;
buffer = strtok (NULL, " ,.-");
}
printf("Second String: %s\n", b); /* Cat eat Dog */
free(b);
free(buffer);
b = NULL;
buffer = NULL;
return (0);
}
output:
Code:
First String: Dog eat Cat
Second String: Cat