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;
}
相关推荐
鬼手点金6 小时前
Scrapy + Playwright 完整示例(JS 动态渲染网页)
开发语言·javascript·爬虫·python·scrapy·html·json
Mr. zhihao6 小时前
深度解析:为什么Java序列化需要搭配ByteArrayOutputStream?IO装饰器模式的精妙设计
java·开发语言·装饰器模式
逆境不可逃6 小时前
【LeetCode 912】排序数组——随机化快速排序详解
数据结构·算法·排序算法
Coder-magician6 小时前
《代码随想录》刷题打卡day31:动态规划-背包问题part02
算法·动态规划
薛定e的猫咪6 小时前
从因果视角解决多智能体协作:细读 SCIC 算法
算法
c238566 小时前
《算法武林谱:四大排序神功与二分寻宝术全解》
数据结构·算法·排序算法
格林威7 小时前
多相机并行采图最佳实践:Task.WhenAll + 异常处理 + 资源释放
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·机器视觉
一米阳光86617 小时前
软考(中级)软件设计师核心笔记(9)算法——时间复杂度与空间复杂度、查找算法、排序算法
笔记·算法·职场发展·软考·软件设计师·中级职称
djjjx.7 小时前
【 C++ 】多态
开发语言·c++·多态
夜雪一千7 小时前
Python如何使用XPath定位没有特征的元素?无id、无class通用定位技巧
开发语言·python