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;
}
相关推荐
严文文-Chris37 分钟前
反向传播算法是什么?和神经网络的关系?
人工智能·神经网络·算法
CoderYanger37 分钟前
动态规划算法-路径问题:10.地下城游戏
开发语言·算法·leetcode·游戏·职场和发展·动态规划·1024程序员节
Drone_xjw37 分钟前
【CPP回调函数】以无人机系统为例梳理回调函数使用
c++·无人机
@小白鸽39 分钟前
1.2.1创建型设计模式
开发语言·设计模式
Tandy12356_39 分钟前
手写TCP/IP协议栈——以太网数据包处理
网络·c++·网络协议·tcp/ip
沐知全栈开发42 分钟前
R 绘图 - 函数曲线图
开发语言
qq_548674931 小时前
Go的env和bashrc的GOROOT配置不同
linux·开发语言·golang
freexyn1 小时前
Matlab自学笔记六十九:多项式求值、求根、积分和求导
开发语言·笔记·matlab