C语言从入门到实战——常用字符函数和字符串函数的了解和模拟实现

常用字符函数和字符串函数的了解和模拟实现

  • 前言
  • 1. 字符分类函数
  • 2. 字符转换函数
  • 3. strlen的使用和模拟实现
  • 4. strcpy的使用和模拟实现
  • 5. strcat的使用和模拟实现
  • 6. strcmp的使用和模拟实现
  • 7. strncpy函数的使用
  • 8. strncat函数的使用
  • 9. strncmp函数的使用
  • 10. strstr的使用和模拟实现
  • 11. strtok函数的使用
  • 12. strerror函数的使用


前言

字符函数和字符串函数都是在编程中用来处理字符和字符串的函数。

字符函数是用来处理单个字符的函数,比如查找、替换、转换大小写、比较等操作。常用的字符函数包括:

  • isalpha():判断一个字符是否为字母;
  • isdigit():判断一个字符是否为数字;
  • islower():判断一个字符是否为小写字母;
  • isspace():判断一个字符是否为空格符;
  • toupper():将一个字符转换为大写字母;
  • tolower():将一个字符转换为小写字母;
  • strchr():在一个字符串中查找指定字符的位置;
  • strstr():在一个字符串中查找指定字符串的位置。

字符串函数是用来处理整个字符串的函数,比如查找、替换、连接、分割等操作。常用的字符串函数包括:

  • strlen():返回一个字符串的长度;
  • strcpy():将一个字符串复制到另一个字符串中;
  • strcat():将一个字符串连接到另一个字符串的末尾;
  • strcmp():比较两个字符串是否相等;
  • strchr():在一个字符串中查找指定字符的位置;
  • strstr():在一个字符串中查找指定字符串的位置;
  • strtok():将一个字符串分割为多个子字符串。

1. 字符分类函数

C语言中有一系列的函数是专门做字符分类的,也就是一个字符是属于什么类型的字符的。

这些函数的使用都需要包含一个头文件是 ctype.h

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

这些函数的使用方法非常类似:

int islower ( int c );

islower 是能够判断参数部分的 c 是否是小写字母。通过返回值来说明是否是小写字母,如果是小写字母就返回非0的整数,如果不是小写字母,则返回0。

练习:

写一个代码,将字符串中的小写字母转大写,其他字符不变。

#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 (islower(c))c -= 32;putchar(c);i++;}return 0;
}

2. 字符转换函数

C语言提供了2个字符转换函数:

int tolower ( int c ); //将参数传进去的大写字母转小写
int toupper ( int c ); //将参数传进去的小写字母转大写

上面的代码,我们将小写转大写,是通过-32完成的效果,有了转换函数,就可以直接使用tolower 函数。

#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 (islower(c))c = toupper(c);putchar(c);i++;}return 0;
}

3. strlen的使用和模拟实现

size_t strlen ( const char * str ); 
  • 字符串以 '\0' 作为结束标志,strlen函数返回的是在字符串中 '\0' 前面出现的字符个数(不包含 '\0' )。
  • 参数指向的字符串必须要以 '\0' 结束。
  • 注意函数的返回值为 size_t,是无符号的( 易错 )
  • strlen的使用需要包含头文件
  • 学会strlen函数的模拟实现
#include <stdio.h>
#include <string.h>
int main()
{const char* str1 = "abcdef";const char* str2 = "bbb";if(strlen(str2)-strlen(str1)>0){printf("str2>str1\n");}else{printf("srt1>str2\n");}return 0;
}

strlen的模拟实现:
方式1:

//计数器方式
int my_strlen(const char * str)
{int count = 0;assert(str);while(*str){count++;str++;}return count;
}

方式2:

//不能创建临时变量计数器
int my_strlen(const char * str)
{assert(str);if(*str == '\0')return 0;elsereturn 1+my_strlen(str+1);
}
//指针-指针的方式
int my_strlen(char *s)
{assert(str);char *p = s;while(*p != ‘\0)p++;return p-s;
}

4. 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).
  • 源字符串必须以 '\0' 结束。
  • 会将源字符串中的 ’\0' 拷贝到目标空间。
  • 目标空间必须足够大,以确保能存放源字符串。
  • 目标空间必须可修改。
  • 学会模拟实现。

strcpy的模拟实现:

//1.参数顺序
//2.函数的功能,停止条件
//3.assert
//4.const修饰指针
//5.函数返回值
//6.题目出自《高质量C/C++编程》书籍最后的试题部分
char *my_strcpy(char *dest, const char*src)
{char *ret = dest;assert(dest != NULL);assert(src != NULL);while((*dest++ = *src++)){;}return ret;
}

5. strcat的使用和模拟实现

  • 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.
  • 源字符串必须以 '\0' 结束。
  • 目标字符串中也得有 \0 ,否则没办法知道追加从哪里开始。
  • 目标空间必须有足够的大,能容纳下源字符串的内容。
  • 目标空间必须可修改。
  • 字符串自己给自己追加,会出现怎么样的情况

模拟实现strcat函数:

char *my_strcat(char *dest, const char*src)
{char *ret = dest;assert(dest != NULL);assert(src != NULL);while(*dest){dest++;}while((*dest++ = *src++)){;}return ret;
}

6. strcmp的使用和模拟实现

  • 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
    • 第一个字符串小于第二个字符串,则返回小于0的数字?
    • 那么如何判断两个字符串? 比较两个字符串中对应位置上字符ASCII码值的大小。

strcmp函数的模拟实现:

int my_strcmp (const char * str1, const char * str2)
{int ret = 0 ;assert(src != NULL);assert(dest != NULL);while(*str1 == *str2){if(*str1 == '\0')return 0;str1++;str2++;}return *str1-*str2;
}

7. 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个字符从源字符串到目标空间。
  • 如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个。

8. 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.
    (将 source指向字符串的前 num个字符追加到 destination指向的字符串末尾,再追加一个 \0 字符)。
  • 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指向的字符串的长度小于num的时候,只会将字符串中到\0 的内容追加到destination指向的字符串末尾)。
/* strncat example */
#include <stdio.h>
#include <string.h>
int main ()
{char str1[20];char str2[20];strcpy (str1,"To be ");strcpy (str2,"or not to be");strncat (str1, str2, 6);printf("%s\n", str1);return 0;
}

9. strncmp函数的使用

int strncmp ( const char * str1, const char * str2, size_t num ); 

比较str1str2的前num个字符,如果相等就继续往后比较,最多比较num个字母,如果提前发现不一样,就提前结束,大的字符所在的字符串大于另外一个。如果num个字符都相等,就是相等返回0.
在这里插入图片描述

10. 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中第一次出现的位置)。
The matching process does not include the terminating null-characters, but it stops there.(字符串的比较匹配不包含 \0 字符,以 \0 作为结束标志)。

/* strstr example */
#include <stdio.h>
#include <string.h>
int main ()
{char str[] ="This is a simple string";char * pch;pch = strstr (str,"simple");strncpy (pch,"sample",6);printf("%s\n", str);return 0;
}

strstr的模拟实现:

char * strstr (const char * str1, const char * str2)
{char *cp = (char *) str1;char *s1, *s2;if ( !*str2 )return((char *)str1);while (*cp){s1 = cp;s2 = (char *) str2;while ( *s1 && *s2 && !(*s1-*s2) )s1++, s2++;if (!*s2)return(cp);cp++;}return(NULL);
}

11. strtok函数的使用

char * strtok ( char * str, const char * sep);
  • sep参数指向一个字符串,定义了用作分隔符的字符集合

  • 第一个参数指定一个字符串,它包含了0个或者多个由sep字符串中一个或者多个分隔符分割的标记。

  • strtok函数找到str中的下一个标记,并将其用 \0 结尾,返回一个指向这个标记的指针。(注:strtok函数会改变被操作的字符串,所以在使用strtok函数切分的字符串一般都是临时拷贝的内容并且可修改。)

  • strtok函数的第一个参数不为 NULL ,函数将找到str中第一个标记,strtok函数将保存它在字符串中的位置。

  • strtok函数的第一个参数为 NULL ,函数将在同一个字符串中被保存的位置开始,查找下一个标记。

  • 如果字符串中不存在更多的标记,则返回 NULL 指针。

#include <stdio.h>
#include <string.h>
int main()
{char arr[] = "192.168.6.111";char* sep = ".";char* str = NULL;for (str = strtok(arr, sep); str != NULL; str = strtok(NULL, sep)){printf("%s\n", str);}return 0;
}

12. strerror函数的使用

char * strerror ( int errnum ); 

strerror函数可以把参数部分错误码对应的错误信息的字符串地址返回来。

在不同的系统和C语言标准库的实现中都规定了一些错误码,一般是放在 errno.h 这个头文件中说明的,C语言程序启动的时候就会使用一个全面的变量errno来记录程序的当前错误码,只不过程序启动的时候errno是0,表示没有错误,当我们在使用标准库中的函数的时候发生了某种错误,就会讲对应的错误码,存放在errno中,而一个错误码的数字是整数很难理解是什么意思,所以每一个错误码都是
有对应的错误信息的。strerror函数就可以将错误对应的错误信息字符串的地址返回。

#include <errno.h>
#include <string.h>
#include <stdio.h>
//我们打印一下0~10这些错误码对应的信息
int main()
{int i = 0;for (i = 0; i <= 10; i++) {printf("%s\n", strerror(i));}return 0;
}

在Windows11+VS2022环境下输出的结果如下:

No error
Operation not permitted
No such file or directory
No such process
Interrupted function call
Input/output error
No such device or address
Arg list too long
Exec format error
Bad file descriptor
No child processes

举例:

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main ()
{
FILE * pFile;
pFile = fopen ("unexist.ent","r");
if (pFile == NULL)
printf ("Error opening file unexist.ent: %s\n", strerror(errno));
return 0;
}

输出:

Error opening file unexist.ent: No such file or directory

也可以了解一下perror函数,perror函数相当于一次将上述代码中的第9行完成了,直接将错误信息打印出来。perror函数打印完参数部分的字符串后,再打印一个冒号和一个空格,再打印错误信息。

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main ()
{FILE * pFile;pFile = fopen ("unexist.ent","r");if (pFile == NULL)perror("Error opening file unexist.ent");return 0;
}

输出:

Error opening file unexist.ent: No such file or directory

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/234650.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MyBatis的强大特性--动态SQL

目录 前言 if trim where set foreach 前言 动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架&#xff0c;你应该能理解根据不同条件拼接 SQL 语句有多痛苦&#xff0c;例如拼接时要确保不能忘记添加必要的空格&#xff0c;还要注意去掉列表…

计算机视觉算法——基于Transformer的目标检测(DN DETR / DINO / Sparser DETR / Lite DETR)

计算机视觉算法——基于Transformer的目标检测&#xff08;DN DETR / DINO&#xff09; 计算机视觉算法——基于Transformer的目标检测&#xff08;DN DETR / DINO&#xff09;1. DN DETR1.1 Stablize Hungarian Matching1.2 Denoising1.3 Attention Mask 2. DINO2.1 Contrasti…

语音信号处理:librosa

1 librosa介绍 Librosa是一个用于音频和音乐分析的Python库&#xff0c;专为音乐信息检索&#xff08;Music Information Retrieval&#xff0c;MIR&#xff09;社区设计。自从2015年首次发布以来&#xff0c;Librosa已成为音频分析和处理领域中最受欢迎的工具之一。它提供了一…

【数据结构】源码角度剖析PriorityQueue

目录 认识 Queue 认识 PriorityQueue PriorityQueue为什么要用二叉堆&#xff1f; PriorityQueue构造方法源码分析 PriorityQueue 的属性 构造方法 JDK1.8传入不可比较的对象 JDK17传入不可比较的对象 传入带有Collection接口的对象 instanceof 关键字 Offer方法分析…

[安洵杯 2019]easy_web

打开环境 img传参还有cmd img应该是base&#xff0c;先解码看看 3535352e706e67 这个好像是十六进制的&#xff0c;再解 访问一下看看&#xff0c;得到一张图片 尝试base解码&#xff0c;但是没有什么发现 再看看地址栏出现index.php,应该是要下载源码&#xff0c;但是还没有…

kafka集群环境部署

文章目录 1 Kafka集群2 搭建两台服务器2.1 zookeeper部署2.2 启动1号机器的broker2.3 启动2号机器的broker2.4 查看kafka集群2.5 测试集群 1 Kafka集群 2 搭建两台服务器 2.1 zookeeper部署 zookeeper先只部署一台&#xff0c;在1号机器&#xff08;192.168.11.59&#xff09;…

windows配置使用supervisor

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、使用步骤1.安装supervisor-win2.配置supervisord3.配置program4.启动supervisord.exe5.supervisorctl.exe管控 二、后台启动总结 前言 windows使用supervi…

基于Java+SpringBoot+Vue3+Uniapp+TypeScript(有视频教程)前后端分离的求职招聘小程序

博主介绍&#xff1a;✌全网粉丝5W&#xff0c;全栈开发工程师&#xff0c;从事多年软件开发&#xff0c;在大厂呆过。持有软件中级、六级等证书。可提供微服务项目搭建与毕业项目实战&#xff0c;博主也曾写过优秀论文&#xff0c;查重率极低&#xff0c;在这方面有丰富的经验…

python技术栈之单元测试中mock的使用

什么是mock&#xff1f; mock测试就是在测试过程中&#xff0c;对于某些不容易构造或者不容易获取的对象&#xff0c;用一个虚拟的对象来创建以便测试的测试方法。 mock的作用 特别是开发过程中上下游未完成的工序导致当前无法测试&#xff0c;需要虚拟某些特定对象以便测试…

[python装饰器]什么是装饰器@

作者&#xff1a;20岁爱吃必胜客&#xff08;坤制作人&#xff09;&#xff0c;近十年开发经验, 跨域学习者&#xff0c;目前于新西兰奥克兰大学攻读IT硕士学位。荣誉&#xff1a;阿里云博客专家认证、腾讯开发者社区优质创作者&#xff0c;在CTF省赛校赛多次取得好成绩。跨领域…

代码随想录算法训练营第30天|回溯总结 332. 重新安排行程

回溯是递归的副产品&#xff0c;只要有递归就会有回溯&#xff0c;所以回溯法也经常和二叉树遍历&#xff0c;深度优先搜索混在一起&#xff0c;因为这两种方式都是用了递归。 回溯法就是暴力搜索&#xff0c;并不是什么高效的算法&#xff0c;最多再剪枝一下。 回溯算法能解…

手把手教会你--办公软件--Word--持续更新

有什么问题&#xff0c;请尽情问博主&#xff0c;QQ群796141573 1.1 Word排版基础1 保存和命名Ⅰ自动保存 2 建立标准的编辑环境(1)显示编辑标记(2)打开标尺(3)打开导航窗格 3 高效的鼠标/键盘手势(1)连续选中内容--shift(2)跳选内容--ctrl(3)矩形选择内容--alt(4)回到文档开头…