码迷,mamicode.com
首页 > 其他好文 > 详细

字符串操作的实现:strstr、strcat、strcmp和stcpy

时间:2015-08-27 15:15:57      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:字符串   strstr   strcat   strcmpcstrcpy   

几个重点强调一下:

(1)注意使用assert;

(2)strcat 和 strcpy最后注意赋值‘\0‘;

(3)strcpy注意内存覆盖的情况;

(4)strcmp中:while(!(ret = *(unsigned char *)s1 - *(unsigned char *)s2) && *s2 != ‘\0‘);???为什么要转换类 型;

(5)strstr函数中返回的类型也要为const。

#include<stdio.h>
#include<assert.h>
#include<string.h>


const char* strstr(const char *s1, const char *s2)
{
    assert(s1 != NULL && s2 != NULL);

    const char *tmp = s1;
    for(; *tmp != '\0'; ++tmp)
    {
        const char *result = tmp;
        const char *tmp1 = s2;
        while(*result == *tmp1 && *tmp1 != '\0')
        {
            ++result;       //++tmp;
            ++tmp1;
        }
        if(*tmp1 == '\0')
            return tmp;    //return result
    }

    return NULL;
}

char *strcat(char *dest, const char *src)
{
    assert(dest != NULL || src != NULL);

    char *tmp = dest;
    while(*tmp != '\0')
    {
        ++tmp;
    }

    while(*src != '\0')
    {
        *tmp = *src;
        ++tmp;
        ++src;
    }
    *tmp = '\0';

    return dest;
}

char *strcpy(char *dest, const char *src)
{
    assert(dest != NULL || src != NULL);

    int length = strlen(src);
    char *result = dest;
    if(dest < src || src + length < dest)
    {
        while(*src != '\0')
        {
            *dest = *src;
            ++src;
            ++dest;
        }
        *dest = '\0';//不能忘了
    }else
    {
        src = src + length - 1;
        dest = dest + length;
        *dest = '\0';
        --dest;
        for(int i = 0; i < length; ++i)
        {
            *dest = *src;
            --src;
            --dest;
        }
    }

    return result;
}

int strcmp(const char *s1, const char *s2)
{
    assert(s1 != NULL || s2 != NULL);

    int ret = 0;

    while(!(ret = *(unsigned char *)s1 - *(unsigned char *)s2) && *s2 != '\0')
    {
        ++s1;
        ++s2;
    }
    
    if(ret < 0)
        return -1;
    else if(ret > 0)
        return 1;
     return ret;
}
int main()
{

    char s1[] = "shui huai li";
    char s2[] = "huai";
    char s3[] = "i am the best";
    char s4[] = "sorry";
    char s6[] = "sorryhe";
    char s5[] = "hello world";
    const char *result = strstr(s1, s3);
    if(result)
        printf("%s\n", result);
    else
        printf("i am sorry!!!\n");
    

    //printf("%s\n", strcat(s1, s5));
    //printf("%s\n", strcpy(s2, s1));
    //printf("%d\n", strcmp(s4, s6));
    return 0;
}




版权声明:本文为博主原创文章,未经博主允许不得转载。

字符串操作的实现:strstr、strcat、strcmp和stcpy

标签:字符串   strstr   strcat   strcmpcstrcpy   

原文地址:http://blog.csdn.net/linuxcprimerapue/article/details/48027775

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!