字符函数和字符串函数第一篇(时间不够,下次再写)
求字符串长度
一 :strlen
实现长度的函数
#include<stdio.h>
#include<assert.h>
int My_strlen(char* arr) {
int count = 0;
assert(arr != NULL);
while (*arr != '\0') {
arr++;
count++;
}
return count;
}
int main() {
char arr[] = "abcdef";
int ret = My_strlen(arr);
printf("%d", ret);
}
2.
#include<stdio.h>
#include<assert.h>
int My_strlen(char* str) {
assert(str);
//start存放的是地址
char *start = str;
while (*str != '\0') {
str++;
}
return str - start;
}
int main() {
char arr[] = "abcdef";
int ret = My_strlen(arr);
printf("%d", ret);
}
3.
通过递归实现
#include<stdio.h>
#include<assert.h>
int My_strlen(char* str) {
assert(str);
//start存放的是地址
if (*str != '\0') {
return 1 + My_strlen(str + 1);
}
return 0;
}
int main() {
char arr[] = "abcdef";
int ret = My_strlen(arr);
printf("%d", ret);
}
二: strcpy
该函数依然有不足之处,拷贝的时候只能拷贝字符串,如果要拷贝数字,不能规定要拷贝的数目,需要用库函数memcpy
实现函数strcpy
#include<stdio.h>
#include<assert.h>
void My_strcpy(char* arr1, char* arr2) {
assert(arr1, arr2);
while (*arr1++ = *arr2++) {
;
}
*arr1 = *arr2;
}
int main() {
char arr1[20] = { 0 };
char arr2[] = "hello bite";
My_strcpy(arr1, arr2);
printf("%s", arr1);
}
三,memcpy函数的实现
1:memcpy 可以拷贝字符串和数字
2:函数memcpy从source的位置开始向后复制num个字节的数据到destination的内存位置。
3:这个函数在遇到 ‘\0’ 的时候并不会停下来。 如果source和destination有任何的重叠,复制的结果都是未定义的。
void * memcpy ( void * destination, const void * source, size_t num );
memcpy的函数实现
/* memcpy example */
#include <stdio.h>
#include <string.h>
struct {
char name[40];
int age;
} person, person_copy;
int main ()
{
char myname[] = "Pierre de Fermat";
/* using memcpy to copy string: */
memcpy ( person.name, myname, strlen(myname)+1 );
person.age = 46;
return 0;
}