转:一些字符串函数的实现

转自:http://blog.chinaunix.net/uid-24194439-id-90780.html

一些字符串函数的实现

http://www.cnblogs.com/JCSU/articles/1305401.html【参考】

这些函数实现最好参考linux内核源码,向大师学习!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *str_cpy(char *dest, const char *src)
{
    int i = 0;
    while(*dest++ = *src++);
    return dest;
}
char str_rev(char *s)
{
    
    char *d = s + strlen(s) - 1;
    char temp;
    while(d > s)
    {
        temp = *d;
        *d = *s;
        *s = temp;
        d--;
        s++;
    }
    
}
static int str_len(const char *s)
{
    int len = 0;
    while(*s++)
        len++;
    return len;


static char *str_cat(char *dest, const char *src)
{
    char *const old = dest;
    while(*dest)
        dest++;
    while(*dest++ = *src++);
    return old;
}
/*static int str_cmp(const char *dst, const char *src)
{    int i = 0;
    while(*(dst + i) == *(src + i))    
    {
        if(*(src+i) == '')
            return 0;
        i++;
    }
    if(*dst > *src)
        return 1;
    else
        return -1;
}*/
int str_cmp(const char * cs, const char * ct)
{
    signed char __res;
    while(1)
    {
        if((__res = *cs - *ct++) != 0 || !cs++)
            break;
    }
    return __res;
}

int main(void)
{
    char a[20]="hello";
    char b[10];
    char c[]="hellz";

    str_cpy(b,a);
    printf("str_cpy:b<-a:%s ", b);

    str_rev(a);
    printf("str_rev:a=%s ", a);

    printf("str_cmp:%d ",str_cmp(a, c));

    str_len(b);    
    printf("str_len:b=%d ", str_len(b));
    
    printf("strcat:a+b:%s ", str_cat(a,c));

    return 0;
}

 
一个简单的回文字符串检测
 

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

static int str_hui(const char *src);

void main(void)
{

    char src[]="abcdcba";

    printf("%s %s ", src, str_hui(src) ? "no" : "yes");
    printf("%s ", src);
}

static int str_hui(const char *src)
{
    const char *end = src;//*end = src + strlen(src) - 1;定位结尾效果相同
    while(*end != '')
        ++end;
    --end;
    while(end >= src)
    {
        if(*src++ != *end--)
        {
            return 1;
        }
    }
    return 0;
}


注意:1,如何定位到文件尾部 2,返回输出的技巧

原文地址:https://www.cnblogs.com/kira2will/p/4019635.html