#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *str[4];
char *ptr = "I am from shanghai";
int i, j;
for (i = 0; i<4; i++)
{
str[i] = (char *)malloc(sizeof(char) * 20);
}
for(i = 0; i < 4; i++)
{
ptr ++;
for (j = 0; j<20; j++)
{
if(*(ptr - 1) == ' ' || *(ptr - 1) == '\0')
{
break;
}
strncat(str[i],ptr - 1, 1);
ptr++;
}
}
for(i = 3; i >= 0; i--)
{
printf("%s ",str[i]);
}
printf("\n");
return 0;
}
还有一种写法:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *str[4];
char *ptr = "I am from shanghai";
int i, j;
for (i = 0; i<4; i++)
{
str[i] = (char *)malloc(sizeof(char) * 20);
}
for(i = 0; i < 4; i++)
{
ptr ++;
for (j = 0; j<20; j++)
{
if(*(ptr - 1) == ' ' || *(ptr - 1) == '\0')
{
break;
}
strncat(str[i],ptr - 1, 1);
ptr++;
}
}
for(i = 3; i >= 0; i--)
{
printf("%s ",str[i]);
}
printf("\n");
return 0;
}