笔记本:
创建时间:
更新时间:
实现标准库的字符串操作函数
strcpy
、
strncpy
、
memmove
、
memcpy
、
memset
、
strlen
、
strncat
、
strcmp
、
strncmp
、
strstr
、
strchr
的
实现
C++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buf
// pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive
copy.
char *strcpy(char *dest, const char *src)
{
assert((src != NULL) && (dest != NULL));
size_t i;
for (i = 0; src[i] != '\0'; i++)
dest[i] = src[i];
dest[i] = '\0';
return dest;
}
// The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte am
the first n bytes of src,
// the string placed in dest will not be null-terminated. If the length of src is less than n, strncpy() pads the remainde
dest with null bytes.
char *strncpy(char *dest, const char *src, size_t n)
{
assert((src != NULL) && (dest != NULL));
size_t i;
for (i = 0; i < n && src[i] != '\0'; i++)
dest[i] = src[i];
for (; i < n; i++)
dest[i] = '\0';
return dest;
}
/*
在
32
位的
x86
平台上
,
每次拷贝
1
个字节需要一条指令
,
每次拷贝
4
个字节也只需要一条指
*
令
,memcpy
函数的实现尽可能
4
个字节
4
个字节地拷贝
*/
void *memcpy(void *dest, const void *src, size_t n)
{
assert((src != NULL) && (dest != NULL));
char *d = dest;
const char *s = src;
int *di;
const int *si;
int r = n % 4;
while (r--)
*d++ = *s++;
di = (int *)d;
si = (const int *)s;
n /= 4;
while (n--)
*di++ = *si++;
return dest;
}
C++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
借助于一个临时缓冲区
temp ,
即使
src
和
dest
所指的内存区间有重叠也能正确拷贝。
*/
void *memmove(void *dest, const void *src, size_t n)
{
assert((src != NULL) && (dest != NULL));
char *temp = (char *)malloc(sizeof(char) * n);
size_t i;
char *d = (char *)dest;
const char *s = (const char *)src;
for (i = 0; i < n; i++)
temp[i] = s[i];
for (i = 0; i < n; i++)
d[i] = temp[i];
free(temp);
return dest;
}
C++ Code
1
2
3
size_t strlen(const char *p)
{
有一些大公司可能会
考,主要是考察基本
功,中小企业考试的不
多。
评论1
最新资源