Simulation implementation of string manipulation functions strlen;strcpy,strncpy;strcmp,strncmp;strcat,strncat;strstr

1. Simulation implementation of character manipulation functions
strlen();strcpy(),strncpy();strcmp(),strncmp();strcat(),strncat();strstr()
//There are points to pay attention to ①Don't forget to assert ;2 Retain the starting address of the original string, which does not exist in the memory copy function
1. Simulate the implementation of strlen(), strlen() is a function used to solve the length of the string, and stops counting when encountering '\0' , so the length of the string required by strlen() does not include the length of '\0'.

//1.1模拟实现strlen,计数器法模拟实现strlen()
int my_strlen1(const  char* str)//const防止字符串被改变
{
    assert(str != NULL);//断言,防止传入空指针,如果是空指针,会抛出异常,空指针不能进行解引用
    int count = 0;
    while(*str != '\0')//对字符串进行解引用,得到字符串里面的值然后与字符串的结尾标志'\0'进行比较
    {
        str++;
        count++;
    }
    return count;
}
//1.2用指针减指针的方法模拟实现strlen
int my_strlen2(const char *str)
{
    assert(str != NULL);
    char *p = str;
    while (*p != '\0')//同样,对指针进行解引用得到字符串里面的真实值然后与'\0'进行比较,知直到将p指针加到字符串的最后一个位置
    {
        p++;
    }
    return p - str;
}
//1.3、用函数递归的方法模拟实现strlen
int my_strlen3(const char *str)
{
    assert(str != NULL);
    if (*str == '\0')
        return 0;
    else
        return 1 + strlen(str + 1);
}

2. Simulate strcpy(), strncpy()
①strcpy() is a standard library function in C language, which copies the string containing '\0' with src as the starting address to the space with dest as the starting address Inside, when '\0' is encountered, the copy ends. When the simulation is implemented, you need to manually copy '\0' into it.
②strncpy() solves the overflow problem of strcpy(), strcpy() is just a string copy function, there is no limit to the number of bytes copied, strncpy() can select a segment of characters to output.
③In general, when using strncpy(), it is recommended to set n as the length of the dest string. After copying, set the last character of the dest string to NUL for insurance.

//2.1模拟实现strcpy()
char* my_strcpy(char *dest, const char *src)//为了保证源字符串不被改变,需要在定义字符串之前加上const修饰;在这里需要注意,目标字符串必须有足够大的空间
{
    assert(dest != NULL&&src != NULL);
    char * address = dest;//保存目标字符串的起始地址,为了从起始地址开始返回拷贝之后的字符串
    while ((*dest++ = *src++))//后置++,先使用,后++,先把源字符串的第一个字符拷到目标字符串中,然后依次向后拷贝,最后再与'\0'进行比较,当指针走到'\0'时,while语句不成立,结束循环
    {
        ;
    }
    *dest = '\0';//需要将'\0'也拷贝进去
    return address;

}
//2.2模拟实现strncpy
//为了避免strcpy造成的溢出现象,可以考虑使用strncpy,srncpy是将源字符串src的n个字符复制到目标dest字符串当中,
//模拟实现strncpy要注意字符串中的'\0',因为它是将字符串中的n个字符拷贝到另一个字符串中,所以并不能确定是否将'\0'拷贝进去
char* my_strncpy(char *dest, const char *src, int n)
{
    assert(dest!=NULL&&src!=NULL);
    char *ret = dest;//保存原始字符串的地址,保存返回值
    while (n)//拷贝n个字符串
    {
        *dest++ = *src++;
        n--;
    }
    if ((*dest - 1) != '\0')//判断是否将'\0'拷贝进去
        *dest = '\0';
        return ret;
}
//3.1模拟实现strcmp(),strcmp()是一个字符串比较函数,s1==s2,返回0;s1<s2,返回负数;
//s1>s2,返回正数,最终结果是返回二者的SASCII值之差
int my_strcmp1(const char *str1, const char* str2)
{
    assert(str1 != NULL);
    assert(str2 != NULL);
    while (*str1 == *str2)
    {
        if (*str1 == '\0')
            return 0;
        str1++;
        str2++;
    }
    return *str1 - *str2;//注意在这块对指针进行解引用,得到ASCII值相减的结果
}

3. The two functions of strcmp and strncmp are both string comparison functions. The result of the comparison is to subtract the ASCII corresponding to the character on the target string dest from the ASCII corresponding to the character on the original string src in the same position.

//3.1模拟实现strcmp,strcmp是一个字符串比较函数,s1==s2,返回0;s1<s2,返回负数;
//s1>s2,返回正数,最终结果是返回二者的SASCII值之差
int my_strcmp1(const char *str1, const char* str2)
{
    assert(str1 != NULL);
    assert(str2 != NULL);
    while (*str1 == *str2)
    {
        if (*str1 == '\0')
            return 0;
        str1++;
        str2++;
    }
    return *str1 - *str2;//注意在这块对指针进行解引用,得到ASCII值相减的结果
}
//3.2模拟实现strcmp
int my_strcmp2(const char *str1, const char *str2)
{
    assert(str1 != NULL);
    assert(str2 != NULL);
    while ((*str1 == *str2) && (*str1 != '\0'))
    {
        str1++;
        str2++;
    }
    return *str1 - *str2;
}
//3.3模拟实现strncmp(),strncmp()是比较两个字符串中前n个字符是否相等,只需要用while语句控制前n个字符即可
int my_strncmp(const char*dest, const char*src,int n)
{
    assert(dest);
    assert(src);
    while (n--)
    {
        if(*dest == *src)//在这里要注意用if-else语句,不用的话就只将第一个字符进行了比较
        {
            dest++;
            src++;
        }
        else 
          return *dest - *src;
    }

}

4. Simulate strcat(), strncat() This is a set of string appending functions, strcat appends the original string src to the end of the target string dest, and strncat appends the n characters of the source string src to After the destination string dest.

//4.1 模拟实现字符串追加函数strcat(),strcat()是一个字符串连接函数,是将字符串str2连接到字符串str1的后面,
//并覆盖str1后面的'\0'
char* my_strcat(char *dest, const char *src)
{
    char *ret = dest;//保存原始字符串的起始地址
    while (*dest != '\0')//在追加字符串之前,需要先把原字符串先便利一遍,找到原字符串的结尾,遍历到'\0'时,循环退出
    {
        dest++;
    }
    while (*dest++ = *src++)
    {
        ;
    }
    return ret;
}
//4.2模拟实现字符串追加函数strncat(),这里是指追加字符串的前n个字符
//用两个while循环,第一个用来遍历目标字符串,找到原字符串的最后一个指针,
//第二个字符串用来完成原字符串向目标字符串的赋值(要注意指针的动态增长)
//在这里要定义一个ret指针,用来记录目标字符串的起始位置,用来准确返回
char* my_strncat(char* dest, const char*src, int n)
{
    assert(dest);
    assert(src);
    char *ret = dest;
    while (*dest)
    {
        dest++;
    }
    while (n--)
    {
        *dest++ = *src++;
    }
    *dest = '\0';
    return ret;
}

5. Simulate strstr(), this
function The overall idea is as follows:
① Set two pointers str, substr, respectively point to the head of the two strings, and then dereference the two pointers
② Compare whether the two dereferenced characters are equal, if they are not equal, str Continue to go backward, substr does not move;
③ When the two pointers are equal, the two pointers go backward at the same time. In addition, pay attention to a special case: str:abbbcdef substr:bbcd, if the above method is used, an error will occur, so when two pointers do not want to wait, str needs to return to the next position of the starting position, so Here you need to set a cp pointer to record the starting position, and at the same
time ’s use the diagram to explain the following two cases:
The first case: search for “bcd” in the string “abcdef” ", the idea is as follows:
write picture description here
obviously this method is problematic for special cases, such as finding "bbcd" in the string "abbbcdef",

write picture description hereIf the traditional method is followed, an error pointer will not be returned


char* my_strstr(const char* dest, const char *src)
{
    assert(dest);
    assert(src);
    char *str = (char*)dest;//,原字符串指针,这里需要强制类型转换
    char *substr = (char*)src;
    char *cp = (char*)dest;//用来保存原字符串的起始地址
    while (*cp)//保证需要比较的原字符串不为空
    {
        str = cp;
        while ((str != '\0') && (substr != '\0') && (*str == *substr))//判断条件是否成立
        {
            str++;
            substr++;
        }
        if (*substr == '\0')//判断字串是否比较完
        {
            return cp;
        }
        substr = src;//当两个指针不相等时,子串需要回到起始位置重新进行比较
        cp++;//原字符串回到起始位置的下一个位置再次进行比较
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326483278&siteId=291194637