首页 > 其他分享 >C语言中常见库函数(1)——字符函数和字符串函数

C语言中常见库函数(1)——字符函数和字符串函数

时间:2024-07-17 17:58:47浏览次数:13  
标签:const 函数 str2 str1 C语言 char 字符串 库函数

文章目录

前言

在编程的过程中,我们经常要处理字符和字符串,为了方便操作字符字符串,C语言标准库中提供了⼀系列库函数,接下来我们就学习一下这些函数。

1.字符分类函数

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

这些函数的使用方法非常类似,我们就用一个函数来举个例子:

int islower(int c);

islower函数能够判断参数部分的c是否是小写字母。

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

2.字符转换函数

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

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

3.strlen的使用和模拟实现

size_t strlen(const char* str);
  • 字符串以\0作为结束标志,strlen函数返回的是在字符串中\0前面出现的字符个数(不包含\0)。
  • 参数指向的字符串必须要以\0结束。
  • 注意函数的返回值为size_t,是无符号的(易错)
  • 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;
	else
		return 1 + my_strlen(str + 1);
}

方式3:

//指针-指针的方式
int my_strlen(char* s)
{
	assert(s);
	char* p = s;
	while (*p != '\0')
		p++;
	return p - s;
}

4.strcpy的使用和模拟实现

char* strcpy(cahr* destination, const cahr* 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的使用和模拟实现

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.

  • 源字符串必须以\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.strncmp的使用和模拟实现

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

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

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 作为结束标志)。

示例代码:

#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的模拟实现:

const char* my_strstr(const char* str1, const char* str2)
{
	assert(str1 && str2);
	const char* s1 = NULL;
	const char* s2 = NULL;
	const char* cur = str1;

	//特殊情况 - str2指向的是空字符串,直接返回str1
	if (*str2 == '\0')
		return str1;

	while (*cur)
	{
		s1 = cur;
		s2 = str2;

		while (*s1 && *s2 && *s1 == *s2)
		{
			s1++;
			s2++;
		}
		if (*s2 == '\0')
			return cur;
		cur++;
	}

	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);
	}//这里巧妙的使用了for循环,使得初始化部分strtok只执行一次,然后都是调整部分strtok的执行。
	return 0;
}

12.strerror函数的使用

char* strerror ( int errnum );

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

在不同的系统和C语言标准库的实现中都规定了⼀些错误码,一般是放在 errno.h 这个头文件中说明的,C语言程序启动的时候就会使用一个全局的变量errno来记录程序的当前错误码,只不过程序启动的时候errno0,表示没有错误,当我们在使用标准库中的函数的时候发生了某种错误,就会将对应的错误码,存放在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+VS2019环境下输出的结果如下:

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

标签:const,函数,str2,str1,C语言,char,字符串,库函数
From: https://blog.csdn.net/2301_80191662/article/details/140493574

相关文章

  • 前端JS箭头函数和普通函数的区别全解 面试必问
    基本语法:普通函数functionfunctionfc(a1,b2,...,pnan){sumnews;}即格式为:funtion 函数名(参数列表) {    语句;    return表达式}2.箭头函数 //当只有一个参数时,圆括号是可选的(singleParam)=>{statements}singleParam=>{......
  • 适用任意复杂转移函数及方程式的 matlab 二维曲线作图与客制化界面
    優點曲線可自行定義粗細,顏色,精細度......等等字可自行定義字體,顏色,大小,方向,位置......等等可自行定義虛線與字來標註曲線上的某一點此方法可延伸至matlab三維曲線或曲面作圖,亦或是同樣概念,但是改用其他程式諸如python來實現前情提要matlab現有表達轉移函數,......
  • 避免函数形参为空指针
    展示一个函数形参为空指针的隐患:执行第32行代码时,相当于执行double*pdPoint=pdTemp;,由于pdTemp=NULL,所以pdPoint=NULL。在然后 voidPointer(double*pdPoint,intiDim)函数中对pdPoint赋了一块动态内存,此时 pdPoint!=NULL,但是 pdPoint和pdTemp只是赋值......
  • 运动会分数统计(数据结构课设)(C语言版)
         本文为数据结构与算法的课程设计《运动会分数统计》的一个分享,使用了顺序表的数据结构。并且将信息以表格的方式打印输出和在txt文件中导入导出。目录1.设计内容和要求2.代码实现1.结构体定义2.全局变量和变量定义3.键盘输入信息4.信息显示5.文件导入导出......
  • C语言中if、else、switch的使用方法
    目录一、if语句1、以下是if语句的语法:2、else的表达形式二、switch语句C语言程序的构建基石是三大基本结构:顺序结构、选择结构(分支)与循环结构。理解这些结构及其组合应用,有助于深入学习并减轻初学者对C语言的畏难情绪。我们可以使用以下5个函数来构成结构体:if、switch(实......
  • C语言中for、while、do while、break、continue、goto的使用方法
    目录一、while循环二、for循环三、dowhile循环四:break和continue语句break语句continue语句goto语句今天介绍一下循环函数for、while、dowhile 然后再看一看break、continue、goto语句循环结构是必须要学习好的,几乎所有代码都会应用到循环结构一、while循环whi......
  • 7.17 C语言程序引言
    一、一个C语言程序运行程序,输入4,输出24,即4的阶乘    C程序由函数(Function,一种子程序)所组成。上述程序涉及4个函数:main()、factorial()、scanf()和printf()。其中,scanf()和printf()是系统事先设计好的函数,分别用于数据的输人和输出:factorial()是程序中定义的函......
  • C语言超市管理系统UI界面
    以下是部分源码,需要源码的+qq:2758566124 #include<easyx.h>#include<stdio.h>#include<stdlib.h>#definewidth1280#defineheight840#definefont_w35//字体宽度#definefont_h90//字体高度typedefstructnode{ charname[100];//名字 charnumb......
  • C语言中的结构体
    前言    在日常使用中,很容易就见到一些使用结构体封装的数据,通过使用结构体,可以编写出更加模块化和易于维护的C程序。在C语言中,结构体(Struct)是一种用户自定义的数据类型,它允许你将不同类型的数据项组合成一个单一的类型。通过使用结构体,你可以表示如学生信息、员工记录......
  • C语言——实验课大作业(十个C语言实验)
    第1关:实验8数学函数任务描述本关任务:编写一个能计算数的正弦、余弦、平方根的小程序。相关知识为了完成本关任务,你需要掌握:调用C语言自带的函数库的方法。导入函数相关库#include<math.h>导入相关库后,可以直接调用相关的函数进行运算,比如计算数a的平方根,可以通过调用s......