1
函数代码:
#include"head.h"
char* create(int size){
char*p=(char*)malloc(size);
return p;
}
void my_invert(char* str){
int len=strlen(str);
int i=0,j=0,k=0;
while(i<len/2){//整体导致
invert(str+i,str+len-i-1);
i++;
}
puts(str);
for(i=0;i<len;i++){
while(*(str+i)==' '){//找到单词的开头
i++;
}
j=i;
while(*(str+j)!=' '&&*(str+j)!=0){//找到单词末尾
j++;
}
k=j;
j--;
while(i<j){
invert(str+i,str+j);//单词内倒置
i++;
j--;
}
i=k;//定位到单词后的空格
}
}
char* my_free(char* str){
if(str==NULL){
return NULL;
}
free(str);
return NULL;
}
void invert(char*p1,char*p2){
int temp=0;
temp=*p1;
*p1=*p2;
*p2=temp;
}
头文件代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
extern char* create(int );
extern void my_invert(char*);
extern char* my_free(char*);
extern void invert(char*,char*);
主函数代码
#include"head.h"
int main(int argc, const char *argv[])
{
char*p=create(32);
printf("请输入字符串");
gets(p);
puts(p);
my_invert(p);
printf("%s\n",p);
p=my_free(p);
return 0;
}
makefile代码
CC=gcc
CFLAGs=-c -Wall -g
EXE=myprogram
OBJS=$(wildcard *.c)
OBJs=$(patsubst %.c,%.o,$(OBJS))
all:$(EXE)
$(EXE):$(OBJS)
$(CC) $^ -o $@
clean:
rm *.o $(EXE)
.PHONY :clean
结果:
ubuntu@ubuntu:invert_str$ make
gcc main.c fun.c -o myprogram
main.c: In function ‘main’:
main.c:6:2: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
gets(p);
^~~~
fgets
/tmp/ccUwP2Kz.o:在函数‘main’中:
main.c:(.text+0x3b): 警告: the `gets' function is dangerous and should not be used.
ubuntu@ubuntu:invert_str$ ./myprogram
请输入字符串this is a book
this is a book
koob a si siht
book a is this