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;
}
相关推荐
我叫黑大帅3 小时前
拒绝加字段堆屎山!利用位掩码与流程编排优雅落地 上图下文 复合状态
后端·算法·面试
罗西的思考4 小时前
【轻量化复刻大模型 / KIMI K3】K3 PostTrain 后训练交互式演示
人工智能·算法·机器学习
Navigator_Z5 小时前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode
yiangL_5 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
JosieBook6 小时前
【鸿蒙开源】把 Windows 任务栏上的流量表搬到鸿蒙 PC:TrafficMonitor 1.86 的 C++ 内核移植实践
c++·windows·harmonyos
电科_银尘6 小时前
【大模型算法与工程 39】PPO:策略比率、裁剪目标与训练稳定性
人工智能·算法·机器学习
shehuiyuelaiyuehao7 小时前
算法68,字符串相乘
算法
Huangjin007_7 小时前
【C++ 算法竞赛篇】STL 常用知识点速通指南
c++·算法
geovindu7 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
skywalk81638 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness