自己动手写字符串库函数 一(C语言实现)

来源:互联网 发布:快剪视频软件 编辑:程序博客网 时间:2024/05/21 13:20

在coding中最常使用的就是对于字符串的处理问题,接下来我们自己动手写库函数,尽量使用指针操作,而不是数组操作

//头文件 string.h#include <stdio.h>#include <stdlib.h>//字符串结构体typedef struct CString{char* str;int len;}string;//初始化void Init(string* str);void Init_With_Len(string* str, int len);void Init_With_Str(string*str, const char*strcopy);//打印字符串void Print_String(string*str);//追加字符void Append_Char(string*str, const char s);//追加字符串void Append_Str(string*str, const char*s);//计算字符串的长度int my_StrLen(const char*str);//字符串复制char* my_StrCopy(string*des, const char*sour);//字符串连接char* my_StrCat(string*des, char* sour);//字符查找char* my_Strchr(string*des, char ch);//字符串查找char* my_FindStr(string*des, char*sour);//删除指定的字符void my_DelChar(string*des, char ch);//指定的位置插入字符void my_InsertChar(string*des, char ch,int pos);//判断是否为空int IsEmpty(string*strs);


//函数的具体实现 string.c#include "String.h"//判断是否为空int IsEmpty(string*strs){//先判断strs是否为空 再判断strs->str是否为空if (strs == NULL || strs->str == NULL)return 0;elsereturn 1;}//获取字符串的长度int my_StrLen(const char*str){if (str == NULL)return -1;int count = 0;while (*str++ != '\0')count++;return count;}//初始化void Init(string* str){str->str = NULL;str->len = 0;}void Init_With_Len(string*str, int len){str->str = (char*)calloc(len, sizeof(char));str->len = len;}void Init_With_Str(string*strs, const char* strcopy){if ( IsEmpty(strs) != 0|| strcopy == NULL)return;else{//计算字符串的长度int count = my_StrLen(strcopy);//注意使用calloc进行空间的分配  count+sizeof(char) 是为了最后一个放入'\0'strs->str = (char*)calloc(count + sizeof(char), sizeof(char));strs->len = count + sizeof(char);//strcpy(strs->str, strcopy);strs->str = my_StrCopy(strs, strcopy);}}//字符串复制char* my_StrCopy(string*des, const char*sour){       if (des->str == NULL || sour == NULL)        return NULL;    char* strTmp = des->str;    int sourLen = my_StrLen(sour);    while (*sour != '\0')        *strTmp++ = *sour++;    *(des->str + sourLen) = '\0';    des->len = sourLen;    return des->str;}//打印字符串void Print_String(string* strs){if (IsEmpty(strs) != 0)printf("%s\n ", strs->str);elsereturn;}

//主函数中测试 main.c#include "String.h"int main(){string strs;Init_With_Str(&strs,"tasklist");     Print_String(&strs);//result: tasklist}




0 0
原创粉丝点击