天天看點

字元串(一)strlen、strcpy、strcat的實作

/傳回字元串的長度
int mystrlen(char *p)
{
    int a = ;
    while ((*p++ )!='\0')
    {
        a++;
    }
    return a;
}
           
//拷貝字元串,将記憶體source上的值存到另一個記憶體上
char *mystrcpy(char *dest,const char *source)
{
    if (dest == NULL || source == NULL)
        return NULL;
    char *p = dest;
    while (*source != '\0')
        *dest++ = *source++;
    *dest= '\0';
    return p;
}
           

1、一定要注意檢查指針,是以這裡傳回char*用于檢查;要新申請一個指針指向dest并傳回這個指針,為什麼不能直接傳回dest呢?因為傳回dest是修改後的值,指針增加後的值,需傳回dest最初的位址。

2、此處的函數調用能更改指針指向的值,并不會更改指針的值

3、此處使用const,是規定該函數範圍内不能更改source指向的内容的值

//拼接字元串,把p2拼到p1後面
char *mystrcat(char *p1,const char *p2)
{
    if (p1 == NULL || p2 == NULL)
        return NULL;
    char *q = p1;
    while (*p1 != '\0')
        p1++;
    while ((*p1++ = *p2++) != '\0');
    return q;
}
           

這裡的p1一定要有足夠的空間,如果主函數是char *ss=”abc”,想要在ss後面拼接就會報錯,因為ss隻有4個位元組(連\0一起)

完整的程式如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//傳回字元串的長度
int mystrlen(char *p)
{
    int a = ;
    while ((*p++ )!='\0')
    {
        a++;
    }
    return a;
}

//拷貝字元串,将記憶體source上的值存到另一個記憶體上
char *mystrcpy(char *dest,const char *source)
{
    if (dest == NULL || source == NULL)
        return NULL;
    char *p = dest;
    while (*source != '\0')//與下面兩行可以合寫成while((*dest++=*source++)!='\0');先指派再判斷是否循環
        *dest++ = *source++;
    *dest= '\0';
    return p;
}

//拼接字元串,把p2拼到p1後面
char *mystrcat(char *p1,const char *p2)
{
    if (p1 == NULL || p2 == NULL)
        return NULL;
    char *q = p1;
    while (*p1 != '\0')
        p1++;
    while ((*p1++ = *p2++) != '\0');
    return q;
}

int main(void)
{
    char c[]="jjj";
    char *b = "hhh";
    char *s = malloc(*sizeof(char));
    char *q = malloc( * sizeof(char));
    gets(s);
    printf("%d\n", mystrlen(s));
    mystrcpy(q, s);
    printf("%s\n", q);
    mystrcat(c, b);
    printf("%s\n", c);
    free(s);
    free(q);
    return ;
}
           

繼續閱讀