2022/12/10、C语言。字符函数和字符串函数

C语言中对字符和字符串的处理很是频繁,但是C语言本身是没有字符串类型的,字符串通常放在常量字符串 中或者 字符数组 中。
字符串常量 适用于那些对它不做修改的字符串函数.

字符函数介绍

strlen

size_t strlen ( const char * str );
  • 字符串以 '\0' 作为结束标志,strlen 函数返回的是在字符串中 '\0' 前面出现的字符个数(不包含 '\0\' )。
  • 参数指向的字符串必须要以 '\0' 结束
  • 注意函数的返回值为 size_t ,是无符号的。

模拟实现:

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

//模拟实现 strlen()函数
size_t my_strlen(const char* str) {
    int count = 0;
    assert(str != NULL);
    while(*str){
        str++;
        count++;
    }
    return count;
}

int main()
{
    
    char * p = "abc123456";
    char * b = "defgh";

    printf("%d \n",my_strlen(p));
    printf("%d \n",my_strlen(b));

    printf("%s \n",p);
    printf("%s \n",b);
    
    return 0;
}

strcpy

char* strcpy(char* destination ,const char* source);
  • Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).–将源指向的C字符串复制到目标指向的数组中,包括结束空字符(并在该点停止)。
  • 源字符必须以 '\0' 结束
  • 会将源字符中的 '\0' 拷贝到目标空间
  • 目标空间必须足够大,以确保能存放源字符串
  • 目标空间必须可变

模拟实现:

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

//模拟实现 strcpy()函数
char* my_strcpy(char* destination,const char* source){

    assert(destination != NULL);
    
    while(*destination){
        *destination = *source;
        if (*source == '\0'){
            break;
        }
        destination++;
        source++;
    }
}

int main()
{

/*
    char *p = "abc123456";  //这种方法是将一个常量字符串的首元素地址,放在了一个char*指针中。
    char *b ="defgh";
    strcpy(b,p);        //无法运行,目标空间不可变。
*/

    char arr[] = "abc123456";   //创建了一个字符数组
    char arr1[] ="defgh";

//    strcpy(arr,arr1);
    my_strcpy(arr,arr1);

    printf("%s \n",arr);
    printf("%s \n",arr1);

    return 0;
}

strcat

char* strcat (char* destination,const char* source)
  • 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. – 将源字符串的副本追加到目标字符串。destination中的终止空字符将被source的第一个字符覆盖,并且在destination中由两者连接形成的新字符串的末尾包含一个空字符。
  • 源字符串必须以 '\0' 结束
  • 目标空间必须有足够的大,能容纳下源字符串的内容。
  • 目标空间必须可修改

模拟实现:

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

//模拟实现 strcat()函数
char *my_strcat(char *destination, const char *source) {

    char* ret = destination;
    assert(destination && source);

    while (*destination) {
        destination++;
    }
    while (*destination++ = *source++) {
        ;
    }
    return ret;
}


int main() {
    char arr[20] = "";   //创建了一个字符数组
    char arr1[] = "defgh";

    my_strcat(arr, arr1);

    printf("%s \n", arr);
    printf("%s \n", arr1);

    return 0;
}

strcmp

int strcmp (const char* str1,const char* str2);
  • 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 null-character is reached. – 这个函数开始比较每个字符串的第一个字符。如果它们相等,则继续处理以下对,直到字符不同或到达终止空字符为止。
  • 标准规定:
    • 第一个字符串大于第二个字符串,则返回大于0的数字
    • 第一个字符串等于第二个字符串,则返回
    • 第一个字符串小于第二个字符串,则返回小于0的数字
    • 判断是根据字符的 ASCII 码大小判断的。
  • 不能传空地址。

模拟实现:

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

//模拟实现 strcmp()函数
int my_strcmp(const char *destination, const char *source) {

    assert(destination != NULL && source != NULL);

    while (1) {
        if ((*destination == *source) && *destination && *source){
            destination++;
            source++;
        }else{
            return *destination - *source;
        }
    }
}

int main() {
    char arr[20] = "accde";   //创建了一个字符数组
    char arr1[20] = "abcd";

    char* p = NULL;

    printf("%d \n", my_strcmp(arr, arr1));

    return 0;
}

strncpy

char* strncpy(char* destination,const char* source,size_t num);
  • Copies the first num characters of source to destination. If the end of the source C string. (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it. – 将源文件的前num个字符复制到目标文件。如果源C字符串结束。(由null字符表示)在复制num个字符之前被找到,目标被填充为0,直到总共写入num个字符为止。
  • 拷贝 num 个字符到目标空间
  • 如果源字符串的长度小于 num ,则拷贝完源字符串之后,在目标的后边追加 0 ,知道num个

模拟实现:

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

//模拟实现 strncpy()函数
char* my_strncpy(char *destination, const char *source,size_t num) {

    int count = 0;
    assert(destination && source);

    while(1){
        if (num == count){
            break;
        }else if(*source == '\0'){
            *destination = '\0';
            destination++;
            count++;
            break;
        }else{
            *destination = *source;
        }
        destination++;
        source++;
        count++;
    }
    while (count<num){
        *destination = '\0';
        count++;
        destination++;
    }
}

//模拟实现 strncpy1()函数 //优化
char* my_strncpy1(char *destination, const char *source,size_t num) {

    while(num && (*destination++ = *source++) != '\0'){
        num--;
    }
    if(num){
        while (--num){
            *destination++ = '\0';
        }
    }
}

int main() {
    char arr[20] = "abcdefghi";   //创建了一个字符数组
    char arr1[20] = "123";

//    char* p = NULL;

    printf("%s\n",arr);
    //strncpy(arr,arr1,5);
    //my_strncpy(arr,arr1,5);
    my_strncpy1(arr,arr1,5);

    for (int i = 0; i <20 ; ++i) {
        printf("%d\t",arr[i]);
    }
    printf("\n");

    printf("%s\n",arr);
    printf("%s\n",arr1);

    return 0;
}

strncat

char* strncat (char* destination,const char* source,size_t num)
  • Appends the first num characters of source to destination, plus a terminating null-character. – 将源文件的第一个num字符附加到目标文件,加上一个终止空字符。
  • If the length of the C string in source is less than num, only the content up to the terminating null-character is copied. – 如果source中C字符串的长度小于num,则只复制到结束空字符的内容。

模拟实现:

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

//模拟实现 strncat()函数
char* my_strncat(char *destination, const char *source,size_t num) {

    while(*destination){
        destination++;
    }

    while(num--){
        *destination = *source;
        if (*source == '\0'){
            break;
        }
        destination++;
        source++;
    }

}

int main() {
    char arr[20] = "abcdefghi";   //创建了一个字符数组
    char arr1[20] = "123456";

//    char* p = NULL;

    printf("%s\n",arr);
    //strncat(arr,arr1,5);
    my_strncat(arr,arr1,5);

    for (int i = 0; i <20 ; ++i) {
        printf("%d\t",arr[i]);
    }
    printf("\n");

    printf("%s\n",arr);
    printf("%s\n",arr1);

    return 0;
}

strncmp

int strncmp(const char* str1,const char* str2,size_t num);
  • 比较到出现另个字符不一样或者一个字符串结束或者num个字符全部比较完。
  • 在这里插入图片描述

模拟实现:

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

//模拟实现 strncmp()函数
int my_strncmp(char *destination, const char *source,size_t num) {

    assert(destination && source);

    while(num--){
        if (*destination == *source){
            destination++;
            source++;
        } else{
            return *destination-*source;
        }
    }
    return 0;

}

int main() {
    char arr[20] = "abcdefghi";   //创建了一个字符数组
    char arr1[20] = "accde";

//    char* p = NULL;

    printf("%s\n",arr);
    //strncat(arr,arr1,5);

    printf("%d\n",my_strncmp(arr,arr1,5));

    return 0;
}

strstr

char* strstr(const char* str1,const char* str2);
  • Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1. – 返回str2在str1中第一次出现的指针,如果str2不是str1的一部分,则返回空指针。

模拟实现:

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

//模拟实现 strstr()函数
char* my_strstr(char *destination, const char *source) {

    assert(destination && source);

    char *str1 = NULL;
    char *str2 = NULL;

    while (1) {
        if (*destination == *source) {
            str1 = destination;
            str2 = source;
            while (*str1 == *str2) {
                str1++;
                str2++;
                if (*str2 == '\0') {
                    return destination;
                }
                if (*str1 == '\0' && *str2 != '\0'){
                    return NULL;
                }
            }
        }

        destination++;
        if (*destination == '\0') {
            return NULL;
        }
    }

}

int main() {
    char arr[20] = "abcdabcde";   //创建了一个字符数组
    char arr1[20] = "bcde";

//    char* p = NULL;

    char* a = NULL;
    a = my_strstr(arr,arr1);
    if (a!=NULL){
        printf("%s",a);
    } else{
        printf("无");
    }

    return 0;
}

strtok

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

使用:

/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
    char str[] ="- This, a sample string.";
    char * pch;
    
    pch = strtok (str," ,.-");  //函数内可能使用的是静态变量保存数据
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ,.-");
    }
    return 0;
}
#include <stdio.h>
#include <string.h>

int main()
{
    char *p = "test@bitedu.tech";
    const char* sep = ".@";
    char arr[30];
    char *str = NULL;
    strcpy(arr, p);//将数据拷贝一份,处理arr数组的内容
    for(str=strtok(arr, sep); str != NULL; str=strtok(NULL, sep))
    {
        printf("%s\n", str);
    }
}

模拟实现:

尝试实现,比较繁琐,问题比较多。

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

//模拟实现strtok()函数
char *my_strtok(char* str, const char *sep) {

    static char *p = NULL; //静态变量,用来记忆
    static  int count = 0;  //计数

    char* s1 = NULL;               //操作数

    if(str!=NULL){          //如果传入的值不为NULL 则赋值传入的值
        p = str;
        s1 = str;
    } else{
        s1 = p;             //否则读取保存的值
    }

    char* ret = s1;         //用来做返回值

    if (str == NULL && p == NULL) {     //如果保存值和传入值都为NULL,则返回NULL
        return NULL;
    }

    int num = strlen(sep);

    while (*s1 != '\0') {       //操作数不为0,不结束循环

        for (int i = 0; i < num; ++i) {
            if (*s1 == *(sep+i)){
                *s1 = '\0';
                p = s1+1;
                count++;
                return ret;
            }
        }   //每一位对比sep

        s1++;   //操作数++

        if (*s1 == '\0') {  //如果前面没有,就将保存至赋值为NULL,
            p = NULL;
            if (count == 0){
                return NULL;
            }
            count = 0;
            return ret;
        }
    }

}

int main() {
    char *p = "test@bitedu.tech";
    const char *sep = "@.";
    char arr[30];
    char *str = NULL;
    strcpy(arr, p);//将数据拷贝一份,处理arr数组的内容
//    for (str = strtok(arr, sep); str != NULL; str = strtok(NULL, sep)) {
//        printf("%s\n", str);
//    }

    for (str = my_strtok(arr, sep); str != NULL; str = my_strtok(NULL, sep)) {
        printf("%s\n", str);
    }

    return 0;
}

strerror

char* strerror(int errnum);

返回错误码对应的错误信息。
调用库函数的时候,调用失败时,都会设置错误码

使用:

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

int main() {

//    printf("%s\n",strerror(0));
//    printf("%s\n",strerror(1));
//    printf("%s\n",strerror(2));
//    printf("%s\n",strerror(3));
//    printf("%s\n",strerror(4));
//    printf("%s\n",strerror(5));

    FILE *pFile;
    pFile = fopen("unexist.txt", "r");
    //文件打开失败的时候会返回NULL
    if (pFile == NULL)
        //printf("Error opening file unexist.txt: %s\n", strerror(errno));
        perror("fopen");
    //errno: Last error number

    return 0;
}

perror 函数,直接打印错误信息
该函数本身会去拿取错误码信息,,首先把错误码转换为错误信息。然后打印错误信息(包含了自定义信息)
strerror 函数,将错误码转化为错误信息,不一定打印

字符分类函数

函数如果他的参数符合下列条件就返回真
iscntrl任何控制字符
isspace空白字符:空格‘ ’,换页‘\f’,换行’\n’,回车‘\r’,制表符’\t’或者垂直制表符’\v’
isdigit十进制数字 0~9
isxdigit十六进制数字,包括所有十进制数字,小写字母a~f,大写字母A~F
islower小写字母a~z
isupper大写字母A~Z
isalpha字母a~z或A~Z
isalnum字母或者数字,a~z,A~Z,0~9
ispunct标点符号,任何不属于数字或者字母的图形字符(可打印)
isgraph任何图形字符
isprint任何可打印字符,包括图形字符和空白字符

需要头文件 #include <ctype.h>

字符转换:

int tolewer(int c);		//转小写,返回小写的 ASCII 码值
int toupper(int c);		//转大写,返回大写的 ASCII 码值
/* isupper example */
#include <stdio.h>
#include <ctype.h>

int main() {
    int i = 0;
    char str[] = "Test String.\n";
    char c;
    while (str[i]) {
        c = str[i];
        if (isupper(c))
            c = tolower(c);
        putchar(c);
        i++;
    }
    return 0;
}



内存函数

memcpy

void* memcpy(void* destination,const void* source,size_t num);
  • 函数memcpy从source的位置开始向后复制num个字节的数据到destination的内存位置。
  • 这个函数在遇到 ‘\0’ 的时候并不会停下来。
  • 如果source和destination有任何的重叠,复制的结果都是未定义的。
/* memcpy example */
#include <stdio.h>
#include <string.h>

struct {
    char name[40];
    int age;
} person, person_copy;

int main() {
    char myname[] = "Pierre de Fermat";
    /* using memcpy to copy string: */
    memcpy(person.name, myname, strlen(myname) + 1);
    person.age = 46;
    /* using memcpy to copy structure: */
    memcpy(&person_copy, &person, sizeof(person));
    printf("person_copy: %s, %d \n", person_copy.name, person_copy.age);
    return 0;
}

memmove

void* memmove(void* destination,const void* source,size_t num);
  • 和memcpy的差别就是memmove函数处理的源内存块和目标内存块是可以重叠的。
  • 如果源空间和目标空间出现重叠,就得使用memmove函数处理。
/* memmove example */
#include <stdio.h>
#include <string.h>
int main ()
{
  char str[] = "memmove can be very useful......";
  memmove (str+20,str+15,11);
  puts (str);
  return 0;
}

模拟实现:

/* memcmp example */
#include <stdio.h>
#include <string.h>

void *my_memmove(void *dst, const void *src, size_t count) {
    void *ret = dst;
    if (dst <= src || (char *) dst >= ((char *) src + count)) {
        /*
         * Non-Overlapping Buffers
         * copy from lower addresses to higher addresses
         */
        while (count--) {
            *(char *) dst = *(char *) src;
            dst = (char *) dst + 1;
            src = (char *) src + 1;
        }
    } else {
        /*
         * Overlapping Buffers
         * copy from higher addresses to lower addresses
         */
        dst = (char *) dst + count - 1;
        src = (char *) src + count - 1;
        while (count--) {
            *(char *) dst = *(char *) src;
            dst = (char *) dst - 1;
            src = (char *) src - 1;
        }
    }
    return (ret);
}

int main ()
{
    char str[] = "memmove can be very useful......";
    my_memmove (str+20,str+15,11);
    puts (str);
    return 0;
}

memcmp

int memcmp ( const void * ptr1, const void * ptr2, size_t num );
  • 比较从ptr1和ptr2指针开始的num个字节
  • 相同返回0;大于返回正数,小于返回负数。
/* memcmp example */
#include <stdio.h>
#include <string.h>

int main() {
    char buffer1[] = "DWgaOtP12df0";
    char buffer2[] = "DWGAOTP12DF0";
    int n;
    n = memcmp(buffer1, buffer2, sizeof(buffer1));
    if (n > 0) printf("'%s' is greater than '%s'.\n", buffer1, buffer2);
    else if (n < 0) printf("'%s' is less than '%s'.\n", buffer1, buffer2);
    else printf("'%s' is the same as '%s'.\n", buffer1, buffer2);
    return 0;
}

memset

/* memcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
    int arr[10] = {0};
    memset(arr,1,20);

    for (int i = 0; i <10 ; ++i) {
        printf("%d \t",arr[i]);
    }
    printf("\n");
    //01 00 00 00       memset是以字节为单位设置内存的
    //01 01 01 01       输入1,操作的时第一个字节的 内容
    printf("16843009 == %x",16843009);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值