方法一:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void my_strcpy(char *result,char *str,int len) //复制长度为len的字符串
{
while(len)
{
*result = *str;
str++;
result++;
len--;
}
}
void change(char *str,char **a)
{
int i = 0; //记录行数
int j = 0;
int count = 0; //记录每行元素的个素
char *temp = NULL;
temp = (char*)malloc(sizeof(char));
while(*str)
{
if(*str == ' '||*str == '\0')
{
my_strcpy(a[i],str-count,count);
i++;
count = 0;
}
count++;
str++;
}
if(*str == '\0')
{
my_strcpy(a[i],str-count,count);
count = 0;
i++;
}
for(j = 0;j < i/2;j++)
{
strcpy(temp,a[j]);
strcpy(a[j],a[i-j-1]);
strcpy(a[i-j-1],temp);
}
for(j = 0;j < i;j++)
{
printf("%s ",a[j]);
}
printf("\n");
free(temp);
}
int main()
{
int i = 0;
char str[] = "I am from shanghai";
char *a[4] = {0};
for(i = 0;i < 4;i++)
{
a[i] = (char*)malloc(sizeof(char)*20);
}
change(str,a);
for(i = 0;i < 4;i++)
{
free(a[i]);
}
return 0;
}
方法二:
#include <stdio.h>
#include <string.h>
void change(char *str)
{
char temp;
char *p = str;
char *start = str;
char *end = str;
while(*p != '\0')
{
p++;
end++;
}
end = p-1;
p = str;
while(*p!='\0')
{
while(start < end)
{
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
p++;
}
}
void change1(char *str)
{
char *p = str;
char *start = p;
char *end = p;
char temp;
while(*p != '\0')
{
if(*p ==' '||*p == '\0')
{
end = p-1;
while(start < end)
{
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
start = end = p+1;
}
p++;
}
end = p-1;
while(start < end)
{
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main()
{
char str[100];
printf("please input string:\n");
gets(str);
change(str);
change1(str);
printf("the result is :%s\n",str);
}