11.字符函数和字符串函数(二)

一.上期回顾

上篇博客的链接如下:

https://blog.csdn.net/weixin_60668256/article/details/155502255?fromshare=blogdetail&sharetype=blogdetail&sharerId=155502255&sharerefer=PC&sharesource=weixin_60668256&sharefrom=from_link

二.strstr的模拟实现

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>

//暴力求解
char* my_strstr(const char* str1, const char* str2)
{
	const char* cur = str1;
	const char* s1 = NULL;
	const char* s2 = NULL;

	assert(str1 && str2);
	if (*str2 == '\0')
	{
		return (char*)str1;
	}

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

int main()
{
	char arr1[] = "abcdef";
	char arr2[] = "abcdef";
	char* ret = my_strstr(arr1, arr2);
	if (ret != NULL)
		printf("%s\n", ret);
	else
		printf("找不到\n");

	return 0;
}

三.strtok函数的使用

cpp 复制代码
#include <string.h>


int main()
{
	char arr[] = "zhangsan@163.com#hehe";
	char arr2[30] = {0}; //zhangsan\0163\0com
	strcpy(arr2, arr);
	const char* p = "@.#";
	char* s = NULL;
	//   初始化部分只执行一次
	for (s = strtok(arr2, p); s != NULL; s=strtok(NULL, p))
	{
		printf("%s\n", s);
	}

	//char *s = strtok(arr2, p);
	//printf("%s\n", s);
	//s = strtok(NULL, p);
	//printf("%s\n", s);
	//s = strtok(NULL, p);
	//printf("%s\n", s);

	return 0;
}

四.strerror函数的使用

cpp 复制代码
int main()
{
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		printf("%d: %s\n",i, strerror(i));
	}

	return 0;
}

将对应的错误码,转换成错误信息

cpp 复制代码
#include <stdio.h>
#include <string.h>
#include <errno.h>

int main()
{
   FILE* pFile;
   pFile = fopen("unexist.txt", "r");
   if (pFile == NULL)
       printf("Error opening file unexist.ent: %s\n", strerror(errno));
   else
       printf("打开文件成功\n");

   return 0;
}
cpp 复制代码
#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));
       perror("Error opening file unexist.ent");
   return 0;
}
相关推荐
为何创造硅基生物2 小时前
C语言 结构体内存对齐规则(通俗易懂版)
c语言·开发语言
吃好睡好便好2 小时前
在Matlab中绘制横直方图
开发语言·学习·算法·matlab
星寂樱易李2 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
仰泳之鹅2 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
之歆3 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
jolimark3 小时前
C语言自学攻略:小白入门三步走
c语言·编程入门·学习路线·实践项目·自学攻略
于小猿Sup4 小时前
VMware在Ubuntu22.04驱动Livox Mid360s
linux·c++·嵌入式硬件·自动驾驶
cen__y4 小时前
Linux12(Git01)
linux·运维·服务器·c语言·开发语言·git
AI人工智能+电脑小能手4 小时前
【大白话说Java面试题 第65题】【JVM篇】第25题:谈谈对 OOM 的认识
java·开发语言·jvm
社交怪人4 小时前
【算平均分】信息学奥赛一本通C语言解法(题号2071)
c语言·开发语言