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;
}
相关推荐
fqbqrr1 小时前
2601C++,cmake与导入
c++
fqbqrr2 小时前
2601C++,编写自己模块
c++
wearegogog1232 小时前
基于 MATLAB 的卡尔曼滤波器实现,用于消除噪声并估算信号
前端·算法·matlab
molaifeng2 小时前
Go 语言如何实现高性能网络 I/O:Netpoller 模型揭秘
开发语言·网络·golang
一只小小汤圆2 小时前
几何算法库
算法
崇山峻岭之间2 小时前
Matlab学习记录33
开发语言·学习·matlab
Evand J2 小时前
【2026课题推荐】DOA定位——MUSIC算法进行多传感器协同目标定位。附MATLAB例程运行结果
开发语言·算法·matlab
jllllyuz3 小时前
基于MATLAB的二维波场模拟程序(含PML边界条件)
开发语言·matlab
leo__5203 小时前
基于MATLAB的交互式多模型跟踪算法(IMM)实现
人工智能·算法·matlab
忆锦紫3 小时前
图像增强算法:Gamma映射算法及MATLAB实现
开发语言·算法·matlab