str类函数

来源:互联网 发布:淘宝卖假的隐形眼镜 编辑:程序博客网 时间:2024/05/18 19:20

strcpy() 将目标字符串复制给源字符串并覆盖源字符串

源代码:

#include<assert.h>//copy字符串char *strcpy(char *src, const char *dst){    assert(NULL != src && NULL != dst);    char *temp = src;   //因为下面*str++程序运行完时str不是指向字符串首位置,所以需要定义一个新的字符串保存字符串首地址    while(*src++ = *dst++);    return temp;}

strncpy() 按照指定字符个数copy字符串

源代码:

#include<assert.h>//按照指定个数copy字符串char *strncpy(char *src, const char *dst, int count){    assert(NULL != src && NULL!= dst);    char *temp = src;    while((count--) && (*src++ = *dst++));//这里要注意count--要在&&前面,不然会出错    *src = '\0';   //由于不是copy整个字符串,所以结尾可能不是\0所以要自己加上    return temp;}

strlen() 求字符串的长度

源代码:#include<assert.h>int strlen(const char *str){    assert(*str != '\0');        //断言,判断字符串是否为空,下同      const char *cp = str;      //str依然为字符串首位置    while(*cp ++);          return (cp - str - 1); //-1是因为字符串末尾有\0, strlen得到的字符串长度没有\0}

strcmp() 判断两个字符串的是否相等

源代码:

#include<assert.h>int strcmp(const char *src, const char *dst){    assert(NULL != src && NULL != dst);    while(*src && *dst && *src++ == *dst++);//当两个字符串都不为空且当前字符串相等时    return *src - *dst;  //返回当前不等字符差值,根据返回值的正负号判断大小}

strcat() 将两个字符串拼接

源代码:

#include<assert.h>//拼接字符串char *strcat(char *src, const char *dst){    assert(NULL != src && NULL != dst);    char *temp = src;    while(*src)   //让src字符串跑到结尾,然后跟strcpy一样实现拼接    {        src ++;    }    while(*src++ == *dst++);    return temp;}

strncat() 按照指定个数实现制定个数字符的拼接

源代码:

#include<assert.h>//按照指定字符个数拼接字符串char *strncat(char *src, const char *dst, int count){    assert(NULL != src && NULL != dst);    char *temp = src;    while(*src)    {        src++;    }    while((count--) && (*src++ = *dst++));    return temp;}
原创粉丝点击