穷不失义,达不离道。——孔丘《论语》
在本章介绍的函数中,都要用到sting.h的头文件。
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.
char* strcpy(char* destination,const char*source);
注意: 1、源字符串必须是以**‘\0 ’**作为结尾。 2、拷贝之后,会将源字符串的 **‘\0’**拷贝到目标空间。 3、目标空间必须足够大,确保能够存放源字符串。 4、目标空间可变。
由于我们知道,strcpy是对于字符串使用的函数,所以可以确定的是传入的数值,是char类型,而不是不清楚的void类型,这样我们就可以少去很多的步骤。
#include<stdio.h>
#include<assert.h>
char* my_strcpy(char* dest, char* src)
{
char* ret = dest;
assert(src);
assert(dest);
while ((*dest++ = *src++))
{
;
}
return ret;
}
int main()
{
char arr1[] = "abds";
char arr2[] = "sssssssss";
my_strcpy(arr2, arr1);
}
值得注意的是,有时候,自己会把数组直接写为arr而不是arr[],这样的话,应该就不是字符串了吧。会导致程序的崩溃。
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination. 注意: 1、源字符串必须要**‘\0’**结束。 2、目标空间必须足够大,能容纳下源字符串的内容。 3、目标字符串中也得有\0,否则不知道从哪个地方开始追加。 4、目标空间必须要可以修改。 那么,自己能给自己修改吗?
char* my_strcat(char* dest, const char* src)
{
assert(dest);
assert(src);
char* ret = dest;
while (*dest)//如果此处*dest写为dest那么就会死循环
{
dest++;
}
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[10] = "sssscccc";
char arr2[100] = "cccccccwwww";
printf("%s", my_strcat(arr2, arr1));
return 0;
}
需要注意的是,在写的过程中,要改确保数组的大小,这是我才写的时候老是会忘记的东西。还有,在写的时候,有时候还会搞错一些*dest和dest的区别,导致程序死循环。 其实strcat在模拟实现的时候,有一半都是上一个strcpy的模拟实现中运用到的,其实区别就是,在strcat中,要把目标字符串的地址先找到\0的位置,这样之后,就相当于,在于用strcpy。
其实是不行的,因为在dest指向\0的时候,src指向开头,但是,第一部的时候就已经把\0,给弄消失了,所以,也就是相当于操作的数组中已经没有\0,也就意味着,这次的操作,将不会停下。所以不能。
首先,先看官方一点的介绍。 This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached. 标准规定: 1、第一个字符串大于第二个字符串,则返回大于0的数。 2、第一个字符串等于第二个字符串,则返回0。 3、第一个字符串小于第二个字符串,则返回小于0的数字。
int my_strcmp(const char* str1, const char* str2)
{
assert(str1 && str2);
while (*str1 == *str2)
{
if (*str1 == '\0')
{
return 0;
}
str1++;
str2++;
}
return *str1 - *str2;
}
其实逐渐熟悉,就i能够掌握好多,开始发现一样的地方和不同的地方。
在strcpy的基础上,增加了n,其实也就是,可以根据自己想要的个数,来进行复制。
也和上面的意思其实差不多,但是如果后面的n大于原来数组的长度,也不会越界,也只会追加原来数组整个的长度。
⽐较str1和str2的前num个字符,如果相等就继续往后⽐较,最多⽐较num个字⺟,如果提前发现不⼀样,就提前结束,⼤的字符所在的字符串⼤于另外⼀个。如果num个字符都相等,就是相等返回0.