字符串处理类

strlen

简单介绍

size_t strlen ( const char * str );

Geting string length.

参数:str,返回值:字符串长度

字符串以\0作为结束标志,返回\0之前的字符个数。返回值是size_t(无符号)。

模拟实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//方法1:计时器
int My_strlen1(char* ps) {
int count = 0;
while (*ps) {
count++;
ps++;
}
return count;
}
//方法2:指针相减
int My_strlen2(char* ps) {
char* start = ps;
while (*ps) {
ps++;
}
return ps - start;
}
//方法3:递归
int My_strlen3(char* ps) {
if (*ps == '\0')
return 0;
else
return 1+My_strlen3(ps+1);
}

strcpy

简单介绍

char * strcpy ( char * destination, const char * source );

Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).

\0结束,且将\0拷贝到目标空间

模拟实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
char* My_strcpy(char* des, char* src) {
char* rst = des;
while (*src) {
*des = *src;
des++;
src++;
}
*des = *src;
return rst;
}
//改进
char* My_strcpy1(char* des, char* src) {
char* rst = des;
while (*des++ = *src++) {
;
}
return rst;
}

strcat

简单介绍

char * strcat ( char * destination, const char * source );

Concatenate strings.

模拟实现

1
2
3
4
5
6
7
8
9
10
11
12
char* My_strcat(char* des, char* src) {
char* ret = des;
//找到des的'\0'
while (*des) {
des++;
}
//字符串拷贝
while (*des++ = *src++) {
;
}
return ret;
}

strcmp

简单介绍

int strcmp ( const char * str1, const char * str2 );

Compare two strings.

模拟实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int My_strcmp(const char* str1, const char* str2) {
while (*str1 == *str2) {
if (*str1 == '\0') {
return 0;
}
str1++;
str2++;
}
if (*str1 > *str2) {
return 1;
}
else{
return -1;
}
}

strstr

简单介绍

const char * strstr ( const char * str1, const char * str2 );

模拟实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const char* My_strstr(const char* str1, const char* str2) {
const char* ps1 = str1;
const char* ps2 = str2;
const char* cur = str1;
while (*ps1) {
ps1 = cur;
while (*ps1 == *ps2 && *ps1 && *ps2) {
ps1++;
ps2++;
}
if (*ps2 == '\0') {
return cur;
}
cur++;
ps2 = str2;
}
return NULL;
}
//*ps1和*ps2不相等时,要重新找ps2在ps1中的位置,ps2复原,ps1继续找下一位(也就是cur的下一位)。

内存操作类

memcpy

简单介绍

void * memcpy ( void * destination, const void * source, size_t num );

Copy block of memory.

模拟实现

1
2
3
4
5
6
7
8
9
void* My_memcpy(void* des, void* src, size_t count) {
void* ret = des;
while (count--) {
*(char*)des = *(char*)src;
des = (char*)des + 1;
src = (char*)src + 1;
}
return ret;
}

memmove

简单介绍

void * memmove ( void * destination, const void * source, size_t num );

Move block of memory,allowing the destination and source to overlap.

模拟实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void* My_memmove(void* des, void* src, size_t count) {
if (des < src) {
//从前向后拷贝
while (count--) {
*(char*)des = *(char*)src;
des = (char*)des + 1;
src = (char*)src + 1;
}

}
else {
//从后向前拷贝
des = (char*)des + count - 1;
src = (char*)src + count - 1;
while (count--) {
*(char*)des = *(char*)src;
des = (char*)des - 1;
src = (char*)src - 1;
}
}