head.h
#ifndef N
#define N
#include <stdio.h>
#include <string.h>
void MyStrRev(char *p);
char *MyStrcat(char *dest,const char *src);
int MyStrcmp(const char *s1,const char *s2);
char *MyStrcpy(char *dest,const char *sec);
long Mystrlen(const char *s1);
int FibonaciRec(int n);
char *WordInversion(char *s);
void BubbleSort(int arr[],int n);
void SimpleRank(int arr[],int n);
#endif
test.c
#include "head.h"
//字符串逆置
//#include <string.h>
void MyStrRev(char *p){
char *p1=p;
char *p2=p+strlen(p)-1;
int temp;
while(p1<p2){
temp=*p1;
*p1=*p2;
*p2=temp;
p1++;
p2--;
}
puts(p);
}
//字符串连接
char *MyStrcat(char *dest,const char *src){
char *p=dest;
while(*dest){
dest++;
}
while(*src){
*dest=*src;
dest++;
src++;
}
*dest=*src;
return p;
}
//字符串比较
int MyStrcmp(const char *s1,const char *s2){
while(*s1){
if(*s1!=*s2){
return *s1-*s2;
}else{
s1++;
s2++;
}
}
return *s1-*s2;
}
//字符串拷贝
char *MyStrcpy(char *dest,const char *sec){
char *p=dest;
while(*sec){
*dest=*sec;
dest++;
sec++;
}
*dest=*sec;
return p;
}
//字符串长度
long Mystrlen(const char *s1){
long count=0;
while(*s1){
count++;
s1++;
}
return count;
}
//递归实现斐波那契
int FibonaciRec(int n){
if(n==1||n==2){
return 1;
}else{
return FibonaciRec(n-1)+FibonaciRec(n-2);
}
}
//实现单词逆置
char *WordInversion(char *s){
char *p=s;
char *p1=s;
char *p2=s+strlen(s)-1;
int temp;
//整体逆置
while(p1<p2){
temp=*p1;
*p1=*p2;
*p2=temp;
p1++;
p2--;
}
//单词逆置
p1=s; //头指针
p2=s; //尾指针
char *t=NULL; //临时存储尾指针
while(*p2){
while(*p2!=' '&&*p2!='\0'){
p2++;
}
t=p2; //保存尾指针在空格处或字符串结尾
p2--;
while(p1<p2){
temp=*p1;
*p1=*p2;
*p2=temp;
p1++;
p2--;
}
p1=t; //将p2的位置给p1,找单词头位置
while(*p1==' '&&*p1!='\0'){
p1++;
}
p2=p1;
}
return p;
}
//指针实现一维数组冒泡排序
void BubbleSort(int arr[],int n){
int *p=arr;
int temp;
int i,j;
for(i=0;i<n-1;i++){
for(j=0;j<n-i-1;j++){
if(p[j]<p[j+1]){
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
}
//指针实现一维数组简单排序
void SimpleRank(int arr[],int n){
int *p=arr;
int i,j,temp;
for(i=0;i<n-1;i++){
for(j=i;j<=n-1;j++){
if(p[i]<p[j]){
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
}
main.c
#include "head.h"
int main(int argc, const char *argv[])
{
char str[64]="hello";
printf("字符串逆置\n");
MyStrRev(str);
printf("\n");
printf("字符串连接\n");
char str1[64]="hello";
char str2[64]="world";
char *p=MyStrcat(str1,str2);
puts(p);
printf("\n");
printf("字符串比较\n");
char str3[64]="hello";
char str4[64]="welcome";
int a=MyStrcmp(str3,str4);
printf("%d\n", a);
printf("字符串拷贝\n");
puts(MyStrcpy(str3,str4));
printf("\n");
printf("字符串长度\n");
printf("%ld\n",Mystrlen(str3));
printf("递归实现斐波那契\n");
int i,n;
printf("请输入:");
scanf("%d", &n);
for(i=1;i<=n;i++){
printf("%d\t", FibonaciRec(i));
}
printf("\n");
printf("单词逆置\n");
char str5[]="hello my student";
puts(WordInversion(str5));
printf("\n");
printf("冒泡排序\n");
int arr1[6]={13,34,213,42,13,32};
int k;
BubbleSort(arr1,6);
for(k=0;k<6;k++){
printf("%d\t", arr1[k]);
}
printf("\n");
printf("简单排序\n");
int arr2[6]={23,43,1,23,53,6};
SimpleRank(arr2,6);
int j;
for(j=0;j<6;j++){
printf("%d\t", arr2[j]);
}
printf("\n");
return 0;
}