首页 > 其他分享 >C语言初阶(四)字符函数和字符串函数

C语言初阶(四)字符函数和字符串函数

时间:2024-08-25 19:26:31浏览次数:8  
标签:初阶 const 函数 str1 C语言 char str 字符串

字符分类函数

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

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

函数    

如果他的参数符合下列条件就返回真

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    任何可打印字符,包括图形字符和空白字符

通过返回值来说明是否是小写字母,如果是小写字母就返回非0的整数,如果不是小写字母,则返回 0。

字符转换函数

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

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

 1.strlen的使用和模拟实现

字符串以 '\0' 作为结束标志

strlen函数返回的是在字符串中 '\0' 前面出现的字符个数(不包含'\0' )

参数指向的字符串必须要以 '\0' 结束

注意函数的返回值为 size_t,是无符号的( 易错 )

strlen的使用需要包含头文件

学会strlen函数的模拟实现

1.计数器

size_t my_strlen1(const char* str)
{
	int count = 0;
	assert(str != NULL);
	while (*str != '\0')
	{
		count++;
		str++;
	}
	return count;
}

2.指针

size_t my_strlen2(const char* str)
{
	const char* start = str;
	assert(str != NULL);
	while (*start != '\0')
	{
		start++;
	}
	return start - str;
}

3.递归

size_t my_strlen3(const char* str)
{
	assert(str != NULL);
	if (*str != '\0')
	{
		return 1 + my_strlen3(str + 1);
	}
	else
		return 0;
}

2.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;
}

3.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;
}

4.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(str1 != NULL);
 assert(str2 != NULL);
 while(*str1 == *str2)
 {
 if(*str1 == '\0')
 return 0;
 str1++;
 str2++;
 }
 return *str1-*str2;
}

5.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个

6.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;
}

7.strncmp函数的使用

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

比较str1和str2的前num个字符,如果相等就继续往后比较,最多比较num个字母

如果提前发现不一样,就提前结束,大的字符所在的字符串大于另外⼀个

如果num个字符都相等,就是相等返回0

8.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);
}

9.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;
}

10.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环境下输出的结果如下:

1No error
2Operation not permitted
3No such file or directory
4No such process
5Interrupted function cal
6l Input/output error
7No such device or address
8Arg list too long
9Exec format error
10Bad file descriptor
11No 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

标签:初阶,const,函数,str1,C语言,char,str,字符串
From: https://blog.csdn.net/cloud_disspated/article/details/140277472

相关文章

  • C语言:函数递归
    目录一、递归1.1递归的思想1.2递归的限制二、递归举例2.1举例1:求n的阶乘 画图推演2.2举例2:顺序打印一个整数的每一位画图推演​编辑  三、递归和迭代一、递归   递归是学习C语言函数绕不开的⼀个话题,那什么是递归呢?递归其实是⼀种解决问题的方法,在C语......
  • Python 字符串反转函数的实现与解析
    Python字符串反转函数的实现与解析在Python编程中,字符串是最常用的数据类型之一。反转字符串是一个常见的编程任务,通常用于数据处理、文本分析和算法练习。本文将详细介绍如何实现一个反转字符串的函数,探讨不同的方法,并分析它们的优缺点。一、字符串反转的基本概念字......
  • 56个JavaScript 实用工具函数助你提升开发效率!
    今天来看看JavaScript中的一些实用的工具函数,希望能帮助你提高开发效率!整理不易,如果觉得有用就点个关注鼓励一下吧!1.数字操作(1)生成指定范围随机数export const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;(2)数字千分......
  • DWS(GAUSSDB)函数返回结果集(表)
    -----------建表------------droptableifexistsemployees;CREATETABLEemployees(employee_idNUMBER(10)PRIMARYKEY,--EmployeeID,primarykeyfirst_nameVARCHAR2(50),--Employee'sfirstnamelast_nameVARCHAR2(50),--Employee'slastna......
  • Linux中的exec族函数
    exec系列函数用于替换当前进程的用户空间代码和数据,从而执行一个新的程序。调用exec系列函数不会创建新的进程,但会用新程序的代码和数据替换当前进程,因此调用exec后,进程的ID保持不变,但进程的行为变为执行新的程序exec系列函数有六个,分别是:execlintexecl(constcha......
  • [vue3] vue3 setup函数
    从语法上看,CompositionAPI提供了一个setup启动函数作为逻辑组织的入口,提供了响应式API,提供了生命周期函数以及依赖注入的接口,通过调用函数来声明一个组件。OptionsAPI选项式API在props、data、methods、computed等选项中定义变量;在组件初始化阶段,Vue.js内部处理这......
  • 反汇编和汇编的区别 怎么用汇编让C语言更小
    在计算机编程的世界中,反汇编和汇编这两个概念往往令人感到深奥而神秘。究竟反汇编和汇编之间有何异同?这是程序员们经常探讨的话题。汇编语言作为一种底层编程语言,与计算机硬件密切相关,而反汇编则是将机器码还原为可读的汇编语言的过程。本文将深入研究反汇编和汇编的区别,帮助......
  • C++函数调用栈从何而来
    竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生~个人主页:rainInSunny | 个人专栏:C++那些事儿、Qt那些事儿目录写在前面原理综述x86架构函数调用栈分析如何获取rbp寄存器的值总结写在前面  程序员对函数调用栈是再熟悉不过了,无论是使用IDE调试还是GDB等工具进行调试,都离......
  • 最全!万字长文总结opencv-python常用函数(一)
    文章目录一,简介:二,图像的基础操作:2.1,图像的读取显示与保存2.1.1图像的读取cv2.imread:2.1.2图像的显示cv2.imshow与等待cv2.waitKey:2.1.3图像保存cv2.imwrite:2.2,图像属性获取:2.3,图像裁剪cv2.selectROI:2.4,图像通道的拆分cv2.split:2.5,图像通道的合并cv2.merge:三,图像的数值......
  • C++函数调用栈从何而来
    竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生~个人主页:rainInSunny | 个人专栏:C++那些事儿、Qt那些事儿文章目录写在前面原理综述x86架构函数调用栈分析如何获取rbp寄存器的值总结写在前面  程序员对函数调用栈是再熟悉不过了,无论是使用IDE调试还是GDB......