1.在堆区申请2个字符类型的大小为20字节的空间。
1> 定义函数,实现在堆区申请空间
2> 定义函数,输入两个字符串
3> 定义函数,计算两个字符串的长度【非函数】
sizeof_t my_strlen(const char *s1) //注意:sizeof_t是unsigned int的别名
4> 定义函数,实现字符串连接
char *my_strcat(const char *dest,const char *src)
5> 定义函数,实现连接后字符串的冒泡排序【是对字符串的每一个字符进行排序】
void Bubble(char *s)
6> 实现字符串逆置
7> 调用函数释放空间
main
#include"herd.h"
int main(int argc, const char *argv[])
{
char*p=create();
char*q=create();
printf("请输入字符串");
input(p);
printf("请输入字符串");
input(q);
int len=my_strlen(p);
int s=my_strlen(q);
printf("字符串长度%d\n",len);
printf("字符串长度%d\n",s);
my_strcat(p,q);
printf("%s\n",p);
Bubble(p);
printf("%s\n",p);
Inversion(p);
printf("逆置后%s\n",p);
p=my_free(p);
q=my_free(q);
return 0;
}
herd.h
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
char *create();
void input(char *p);
size_t my_strlen(char*p);
char *my_strcat(char *dest,char *str);
void Bubble(char *s);
void Inversion(char *b);
char *my_free(char*p);
test.c
#include"herd.h"
char *create()
{
char *p=(char*)malloc(sizeof(char)*32);
if(p==NULL){
return NULL;
}
return p;
}
void input(char *p)
{
scanf("%s",p);
}
size_t my_strlen(char *s1)
{
int len=0;
while(*s1!='\0'){
len++;
s1++;
}
return len;
}
char *my_strcat(char *dest,char *str)
{
char *tst=dest;
while(*tst!='\0'){
tst++;
}
while(*str!='\0')
{
*tst=*str;
tst++;
str++;
}
return dest;
}
void Bubble(char *s)
{
for(int i=1;i<my_strlen(s);i++){
for(int j=0;j<my_strlen(s)-i;j++){
if(*(s+j)>*(s+j+1)){
char atc=*(s+j);
*(s+j)=*(s+j+1);
*(s+j+1)=atc;
}
}
}
}
void Inversion(char *b)
{
int l=my_strlen(b);
for(int i=0;i<l/2;i++){
int temp=*(b+i);
*(b+i)=*(b+l-1-i);
*(b+l-1-i)=temp;
}
}
char *my_free(char*p)
{
if(p==NULL)
return NULL;
free(p);
p=NULL;
return p;
}
结果