1 my_strlen()
求字符串有效字符个数
#include<stdio.h>
int my_strlen(const char* arr) {
if (arr == NULL) {
return 0;
}
int count = 0;
while (*arr++ != '\0') {
//arr++;
count++;
}
return count;
}
int main() {
char arr[] = "hello";
int len = my_strlen(arr);
printf("%d\n", len);//5
}
2 my_strcmp()
比较两个字符串大小
#include<stdio.h>
/*
* 进行两个字符串的比较时:
* -2表示两个字符中有一个为空
* 0表示两个字符相等
* -1表示前者小于后者
* 1表示前者大于后者
*/
int my_strcmp(const char* a,const char* b) {
if (a == NULL || b == NULL) {
return -2;
}
int result = 0;
while (*a == *b) {
if (*a == '\0') {
return result;
}
a++;
b++;
}
if (*a != *b) {
result = *a > *b ? 1 : -1;
}
return result;
}
int main() {
int f1 = my_strcmp("a","A");//1
int f2 = my_strcmp("abc","abc");//0
int f3 = my_strcmp("abc","abc\0def");//0 遇到'\0'结束比较
int f4 = my_strcmp("abc","adef");//-1
printf("%d\n", f1);
printf("%d\n", f2);
printf("%d\n", f3);
printf("%d\n", f4);
}
3 my_strcat()
完成两个字符串的链接
#include<stdio.h>
#include <cassert>
void my_strcat(char* a,const char* b) {
assert(a != NULL && b != NULL);
while (*a != '\0') { //让a定位到\0位置
a++;
}
while (*b != '\0') {
*a++ = *b++;
}
*a = '\0';
}
int main() {
char a[128] = "hello";
my_strcat(a, " world!");
printf("%s\n", a);//hello world!
}
4 my_strcpy()
完成字符串的拷贝
#include<stdio.h>
#include <cassert>
void my_strcpy(char* a,const char* b) {
assert(a != NULL && b != NULL);
while (*b != '\0') {
*a++ = *b++;
}
*a = '\0';
}
int main() {
char a[20];
my_strcpy(a, "happy");
printf("%s\n", a);
}
5 assert()函数
assert()是一个调试程序时经常使用的宏,在程序运行时它计算括号内的表达式,如果表达式为0, 程序将报告错误,并终止执行。如果表达式不为0,则继续执行后面的语句。这个宏通常原来判断程序中是否出现了明显非法的数据,如果出现了终止程序以免导致严重后果,同时也便于查找错误。
注意:ASSERT只有在Debug版本中才有效,如果编译为Release版本则被忽略。
assert()的使用:
- 空指针检查。assert (a != NULL);这样,当出现空指针时,你的程序就会退出,并很好的给出错误信息。
- 检查函数参数的值。如果一个函数只能在它的一个参数flag为正值的时候被调用,你可以在函数开始时这样写:assert (flag > 0)。