C语言之库函数的模拟与使用

 

C语言之库函数的模拟与使用

 

在我们学习C语言的过程中,难免会遇到这样的一种情况:

我们通常实现一个功能的时候,费尽心血的写出来,却有着满满的错,这时却有人来告诉你说:这个功能可以用相应的库函数来实现。

这时你的心里充满着***。但这并不算坏事,至少加深了你对它的认识与记忆。

 

所以,今天来漫谈一下 某些库函数的模拟与实现。

而这篇我们主要来介绍一些处理字符和字符串的库函数的使用和注意事项

内容大致如下:

1.求字符串长度 strlen

2.长度不受限制的字符串函数 strcpy strcat strcmp

3.长度受限制的字符串函数介绍 strncpy strncat strncmp

4.字符串查找 strstr strtok

5.错误信息报告 strerror perror

6.字符操作

7.内存操作函数 memcpy memmove memset memcmp

1.求字符串长度--strlen

 

 

正如所介绍那样,此函数的功能就是求一个字符串的长度。而我们所需要做的就是传一个字符指针进去。

示例:

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

int main ()
{
  char szInput[256];
  printf ("Enter a sentence: ");
  gets (szInput);
  printf (The sentence entered is %u characters long.\n,(unsigned)strlen(szInput));
  return 0;
}

结果:

在此函数的使用过程中我们需要注意以下几点:

1.字符串已经 '\0' 作为结束标志
2.strlen函数返回的是在字符串中 ' 前面出现的字符个数(不包含 )。
3.参数指向的字符串必须要以 结束。
4.注意函数的返回值为size_t,是无符号的( 易错 )

我们来看一个对于第四点的例子:

#include <stdio.h> 
#include<string.h>
 main()
{
    const char* str1 = abcdef; 
    char* str2 = bbbif (strlen(str2) - strlen(str1) > )
    {
        printf(str2>str1\n);
    }
    else
    {
        printf(srt1>str2\n;
}

这个结果会是什么呢?

相信会有人给出srt1>str2的结果,可编译器给出的结果却是:

 

 

 为什么呢?

我们原以为 3-6=-3 这个式子没错啊,-3<0 执行 else 的结果

但 因为strlen的返回类型是一个unsigned形,所以相减之后的那个数会变为一个很大很大的数。

 

我们来模拟实现一下此函数

1.计数器方式

int my_strlen(char* str)
{
    int count = ;
    while (*str)
    {
        count++; 
        str++;
    }
    return count;
}

2.递归实现

if (*str == )
        else
        1 + my_strlen(str + 1);
}

3.指针-指针 实现

 

 s)
{
    char* p = s;
    while (*p != )
        p++return p - s;
}

 

2.长度不受限制的字符串函数

1.strcpy

这个函数可谓是见名知意,字符串的拷贝函数,我们来看看介绍:

实例:

#include <stdio.h>char str1[] = Sample stringchar str2[40];
    char str3[];
    strcpy(str2,str1);
    strcpy(str3,copy successful);
    printf(str1: %s\nstr2: %s\nstr3: %s\n;
}

上述代码干了一个什么事呢?

将str1中的内容拷贝到str2中

又将 copy successful  拷贝到str3中

结果:

 

同样注意以下几点:

Copies the C string pointed by source into the array pointed by destination,including the terminating null character (and stopping at that point).
源字符串必须以
结束。
会将源字符串中的
拷贝到目标空间。
目标空间必须足够大,以确保能存放源字符串。目标空间必须可变。

模拟实现strcpy

#include<assert.h>
char* my_strcpy(char* dest, src)
{
    char* ret = dest;
    assert(dest != NULL); //断言保证dest不为空指针
    assert(src != NULL);  断言保证src不为空指针

    while ((*dest++ = *src++))
    {
        ;
    }
     ret;
}

2.strcat-连接两个字符串

介绍如下:

 

 实例:

#include <stdio.h>char str[80];
    strcpy(str,1)">these );
    strcat(str,1)">strings are concatenated.);
    puts(str);
    ;
}

作用:

先将 these 复制到 str 中,在逐次将 strings 、are、concatenated 连接到str上

结果:

 

 注意:

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.源字符串必须以  结束。

2.目标空间必须有足够的大,能容纳下源字符串的内容。目标空间必须可修改。

还值得注意的一点就是:若自己追加自己将会“永无休止”的循环下去,为什么呢?

 

 

模拟实现

#include<assert.h>
char* my_strcat( dest; 
    assert(dest != NULL); 
    assert(src != NULL); 
    while (*dest)            找到\0的位置
    {
        dest++while ((*dest++ = *src++))在此\0位置上覆盖新的内容
    {
        ;
    }
     ret;
}

 

3.strcmp-字符串比较函数

切记:不能用 == 来判断两个字符串是否相等

介绍:

 

 实例:

#include <stdio.h>char key[] = applechar buffer[do {
        printf(Guess my favorite fruit? );
        fflush(stdout);
        scanf(%79swhile (strcmp(key,buffer) != );
    puts(Correct answer!);
    ;
}

 作用:

定义一个key来表示自己喜欢的水果,

让用户不断来输入,

直到用户输入所指定内容

最后输出 correct answer

 结果:

 

 注意:

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 is reached.

标准规定:
第一个字符串大于第二个字符串,则返回大于0的数字
第一个字符串等于第二个字符串,则返回0
第一个字符串小于第二个字符串,则返回小于0的数字

比较是比的相应字符的ASCII码值,如果相等,则比较下一个以此类推.....

 

 模拟实现:

 

int my_strcmp(char* src,1)"> dest)
{
    int ret = ;
    assert(src != NULL); 
    assert(dest != NULL);
    while (!(ret = *(unsigned char*)src - *(unsigned char*)dest) && *dest)dest不为空,且如果相减结果为0,就继续循环
    {
        ++src,++dest;

        if (ret < )
            ret = -; 
        else if (ret > )
            ret = ;

    }
    
    (ret);
}
#include<assert.h>
char*s1,1)">s2)
{
    assert(s1 && s2);
    while (*s1 == *s2)
    {
        if (*s1 == )
            ;
        s1++;
        s2++return *s1 - *s2;
}

 

3.长度受限制的字符串函数介绍

1.strncpy-从原始串复制自定义个字符到新串中

介绍:

 

 实例:


#include <stdio.h>char str1[]= To be or not to be;
  ];
  ];

  /* copy to sized buffer (overflow safe): */
  strncpy ( str2,sizeof(str2) );

   partial copy (only 5 chars): 
  strncpy ( str3,1)">5 );
  str3[5] = ';    null character manually added 

  puts (str1);
  puts (str2);
  puts (str3);

  0;
}

作用:

将str1中所有的字符复制到str2中

将str1中的前五个字符复制到str3中

结果:

 

 注意:

Copies the first num characters of source to destination. If the end of the source C string (which 
signaled by a null-character) is found before num characters have been copied,destination  padded
with zeros until a total of num characters have been written to it.
拷贝num个字符从源字符串到目标空间。 如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个。

模拟实现:

char* my_strncpy(char* destination,1)"> source,size_t num)
{
    assert(destination && source);
     destination;
    destination[num] = while (num--)
    {
        if (*source == )
        {
            *destination = ;
            break;
        }
        *destination++ = *source++ ret;
}

 

2.strncat--从原始串取自定义个字符连接到新串中

介绍:

 

 

 示例:

#include <stdio.h>char str1[20];
    strcpy(str1,1)">To be );
    strcpy(str2,1)">or not to be);
    strncat(str1,1)">6);
    puts(str1);
    ;
}

作用:

将str2中的前6个字符连接到str1后面

结果:

 

注意:

Appends the first num characters of source to destination,plus a terminating null-character.
If the length of the C string in source is less than num,only the content up to the terminating nullcharacter is copied.

 

 

 模拟实现:

char* my_strncat( destination;
    while (*destination);找到\0
    destination[num] = ';放置\0
    )
    {
        *destination++ = *source++;
        ;
        }
    }
     ret;
}

3.strncmp-自定义个字符比较

比较方式与strcmp相同

介绍:

 

 

 示例:

#include <stdio.h>char str[][5] = { R2D2",C3POR2A6 };
     n;
    puts(Looking for R2 astromech droids...for (n = 0; n < 3; n++if (strncmp(str[n],1)">R2xx2) == )
        {
            printf(found %s\n;
}

作用:

比较各字符串的前两个字符是否为R2,如果相同,则输出

结果:

 

 

 注意:

比较到出现另个字符不一样或者一个字符串结束或者num个字符全部比较完。

 

模拟实现:

#include <stdio.h>int my_strncmp(char* str1,1)"> str2,size_t num)
{
    assert(str1 && str2);
    if ((*str1 != *str2))
        {
            return *str1 - *str2;
        }
        str1++;
        str2++;
}

4.字符串查找函数

1.strstr-在一个字符串中查找另一个字符串是否存在并返回相应的地址

介绍:

 

 

 示例:

#include <stdio.h>char str[] = This is a simple string pch;
    pch = strstr(str,1)">simpleif (pch != NULL)
        strncpy(pch,1)">sample);
    puts(pch);
    ;
}

作用:

在str中查找simple是否存在

结果:

 

 

 注意:

Returns a pointer to the first occurrence of str2 in str1,or a null pointer if str2 is not part of str1.

模拟实现:

#include <stdio.h>char* my_strstr( str2)
{
    assert(str1 &&char* start = str1;
    start)
    {
        char* e1 = start;
        char* e2 = str2;
        while ((*e1 == *e2) && (*e1) && (*e2))
        {
            e1++;
            e2++;
        }
        if (*e2 == )
        {
            return ()start;
        }
        start++ NULL;
}

2.strtok-字符串分割函数

介绍:

 

 

 实例:

#include <stdio.h>EG:- This,a sample string. pch;
    printf(Splitting string \"%s\" into tokens:\nwhile (pch != NULL)
    {
        printf(%s\n;
}

作用:

将所给字符串用所给分隔符分割开;

结果:

 

 

 注意:

char * strtok ( char * str,1)">char * sep );
sep参数是个字符串,定义了用作分隔符的字符集合
第一个参数指定一个字符串,它包含了0个或者多个由sep字符串中一个或者多个分隔符分割的标记。
strtok函数找到str中的下一个标记,并将其用 \
结尾,返回一个指向这个标记的指针。(注:strtok函数会改 变被操作的字符串,所以在使用strtok函数切分的字符串一般都是临时拷贝的内容并且可修改。)
strtok函数的第一个参数不为 NULL ,函数将找到str中第一个标记,strtok函数将保存它在字符串中的位置。
strtok函数的第一个参数为 NULL ,函数将在同一个字符串中被保存的位置开始,查找下一个标记。
如果字符串中不存在更多的标记,则返回 NULL 指针。

 

5.错误信息报告

 

 

 

 1.strerror-返回错误码,所对应的错误信息。

介绍:

 

 

 示例:

#include <stdio.h>string.h>
#include <errno.h>//必须包含的头文件

 main()
{
    FILE* pFile;
    pFile = fopen(unexist.entrif (pFile == NULL)
        printf(Error opening file unexist.ent: %s\n;
}

结果:

 

 

 注意:

使用时必须包含头文件:errno.h

2.perror-打印对应的错误信息

 

 

 示例:

#include <stdio.h>

rb NULL)
        perror(The following error occurred
        fclose(pFile);
    ;
}

结果:

 

 

 

6.字符分类函数:

 

 

 注意:

比较时,是一个一个字符的去比较

示例及结果:

#include <stdio.h>
#include <ctype.h>
 i;
  char str[]=c3po...;
  i=while (isalnum(str[i])) i++;
  printf (The first %d characters are alphanumeric.\n;
}

 

 

 

#include <stdio.h>int i = C++while (str[i])
    {
        if (isalpha(str[i])) 
            printf(character %c is alphabetic\n 
            printf(character %c is not alphabetic\n;
}

 

 

 

7.内存操作函数

内存操作函数不仅可以处理字符串,还可以处理结构体,整形数组等。

1.memcpy--以字节为单位复制

介绍:

 

 

 示例:

#include <stdio.h>struct {
    char name[ age;
} person,person_copy;

char myname[] = Pierre de Fermat;

     using memcpy to copy string: 
    memcpy(person.name,myname,strlen(myname) + );
    person.age = 46 using memcpy to copy structure: 
    memcpy(&person_copy,&person,1)">(person));

    printf(person_copy: %s,%d \n;
}

结果:

 

 

 注意:

void * memcpy ( void * destination,const void * source,size_t num );

函数memcpy从source的位置开始向后复制num个字节的数据到destination的内存位置。
这个函数在遇到
的时候并不会停下来。
如果source和destination有任何的重叠,复制的结果都是未定义的

模拟实现:

void* my_memcpy(void* destination,1)">void*void* ret =)
    {
        *((char*)destination)++ = *((char*)source)++ ret;
}

2.memmove

介绍:

 

 

 示例:

#include <stdio.h>memmove can be very useful......;
  memmove (str+20,str+15,1)">11);
  puts (str);
  ;
}

结果:

 

 注意:

memmove和memcpy的差别就是memmove函数处理的源内存块和目标内存块是可以重叠的。

如果源空间和目标空间出现重叠,就得使用memmove函数处理。

模拟实现:

void* my_memmove(void* dest,1)">src,size_t count)
{
     dest;
    assert(dest && src);
    if (dest < src)
    {
        前->后
        while (count--)
        {
            *(char*)dest = *()src;
            ++()dest;
            ++()src;
        }
    }
    
    {
        后->前
        )
        {
            *((char*)dest + count) = *((char*)src + count);
        }
    }
     ret;
}

3.memset

介绍:

 

 示例:

#include <stdio.h>almost every programmer should know memset!;
  memset (str,1)">-',1)">;
}

结果:

 

 模拟实现:

void * Memset(void* src,1)"> ch,size_t count)
{
    assert(src !=void* start = src;
    )
    {
        *(char*)src = (char)ch;
        src = (char*)src +  start;
}

4.memcmp

介绍:

 

 示例:

#include <stdio.h>char buffer1[] = DWgaOtP12df0char buffer2[] = DWGAOTP12DF0;

   n;

  n=memcmp ( buffer1,buffer2,1)">(buffer1) );

  if (n>0) printf ('%s' is greater than '%s'.\nif (n<'%s' is less than '%s'.\nelse printf ('%s' is the same as '%s'.\n;
}

结果:

 

 注意:

比较从ptr1和ptr2指针开始的num个字节

返回值同strcmp

模拟实现:

int my_memcmp(void* p1,1)">void* p2,size_t count)方法1
{
    assert(p1);
    assert(p2);
    char* dest = ()p1;
    char* src = ()p2;
    while (count-- && (*dest++ == *src++if (count == return *dest - *src;
}

 

 

 

若有有错之处,还望大家多多指点!!!

 

本次讲解就到这了,

如果大家对于函数的模拟实现都能掌握,那么大家肯定对于上述函数有了深刻的理解。

 

相关文章

一.C语言中的static关键字 在C语言中,static可以用来修饰局...
浅谈C/C++中的指针和数组(二) 前面已经讨论了指针...
浅谈C/C++中的指针和数组(一)指针是C/C++...
从两个例子分析C语言的声明 在读《C专家编程》一书的第三章时...
C语言文件操作解析(一)在讨论C语言文件操作之前,先了解一下...
C语言文件操作解析(三) 在前面已经讨论了文件打开操作,下面...