C 语言实现了下字符串的基本操作,包括求长度、复制、拼接、判断是否相等、全大写、全小写几个函数,完整代码如下,其中还有些不合理之处,暂时没想到如何修改,对于理解指针和字符数组还是有一定帮助的。
// File name: main.c // Created by lbt on 2020-10-3. // Description: test functions of string operation #include <stdio.h> #include "str.h" int main(void){ char str1[10] = "abCd"; char* str2; char str3[] = "abcd"; printf("length of \"%s\" is %d\n", str1, StrLen(str1)); StrCopy(str2, str1); printf("str1 is \"%s\"\nafter StrCopy(str2, str1), str2 is \"%s\"\n", str1, str2); UpperCase(str2); printf("Upper cases of str2 is \"%s\"\n", str2); LowerCase(str2); printf("Lower cases of str2 is \"%s\"\n", str2); if(!IsEqual(str2, str3)) printf("str2(\"%s\") is different from str3(\"%s\")\n", str2, str3); else printf("str2(\"%s\") is the same as str3(\"%s\")\n", str2, str3); printf("str2(\"%s\") + str3(\"%s\") is \"%s\"\n", str2, str3, StrCat(str2, str3)); return 0; } // File name: str.h // Created by lbt on 2020-10-3. // Description: head file of string operations #ifndef C_STR_H #define C_STR_H #include <stdlib.h> #define bool int size_t StrLen(char *str); char *StrCopy(char* des, char *src); void UpperCase(char *str); void LowerCase(char *str); bool IsEqual(char *str1, char *str2); char* StrCat(char *des, char *src); #endif //C_STR_H // File name: str.c // Created by lbt on 2020-10-3. // Description: source file of string operation #include <assert.h> #include "str.h" #define true 1 #define false 0 size_t StrLen(char *str){ if(!str) return 0; char *p = str; while(*p){ p++; } return p - str; } char* StrCopy(char *des, char *src){ assert(des != NULL && src != NULL); char *p = des; while(*p++ = *src++) ; return des; } void UpperCase(char *str){ if(!str) return; while(*str){ if(*str <= 'z' && *str >= 'a') *str += 'A' - 'a'; str++; } } void LowerCase(char *str){ if(!str) return; while(*str){ if(*str <= 'Z' && *str >= 'A') *str -= 'A' - 'a'; str++; } } bool IsEqual(char *str1, char *str2){ if(StrLen(str1) != StrLen(str2)){ return false; } if(!str1 && !str2) return true; while(*str1 != '\0') if(*str1++ != *str2++) return false; return true; } char *StrCat(char *des, char *src){ if(!src) return des; char* p = des; assert(des != NULL); while(*p) p++; while(*p++ = *src++) ; return des; }