c++学习笔记(7)

strstr函数 

char* *strstr(const char *str1,const char *str2)

在str1里查找str2的位置 如果没有则返回NULL


#include "stdio.h"
#include "stdlib.h"
#include "string.h"

void main81()
{
	char *p = "abcd1111abcd2222abcd333qqq";
	char *p2 = NULL;
	p2 = strstr(p, "q");
	p2 = strchr(p, 'q');//在字符串里查找q第一次出现的位置
	if (p2 == NULL)
	{
		printf("没有找到\n");
	}
	else
	{
		printf("找到:%s\n",p2);
	}

	system("pause");
}

void main82()
{
	int count = 0;
	char *sub = "abcd";
	char *p = "abcd1111abcd2222abcd333qqq";
	char *p2 = NULL;
	do
	{
		p = strstr(p, sub);
		if (p != NULL)
		{
			count++;
			p = p + strlen(sub);
		}
		else
		{
			break;
		}
	} while (*p != '\0');
	printf("count = %d\n", count);

	system("pause");
}

void main83()
{
	int count = 0;
	char *sub = "abcd";
	char *p = "abcd1111abcd2222abcd333qqq";
	while (p = strstr(p, sub))
	{
		count++;
		p = p + strlen(sub);
		if (*p == '\0')
		{
			break;
		}
	}
	printf("count = %d\n", count);
	system("pause");
}

int strstrCount(char *p, char *p2, int *cout) //返回的值也要做成指针形参 不要直接用int类型函数返回
{
	int count = 0;
	int ret = 0;
	if (p == NULL || p2 == NULL || cout == NULL)
	{
		ret = -1;
		return ret;
	}
	while (p = strstr(p, p2))
	{
		count++;
		p = p + strlen(p2);
		if (*p == '\0')
		{
			break;
		}
	}
	*cout = count;
	return 0;
}

void main()
{
	int count = 0;
	int ret = 0;
	char *p2 = "abcd";
	char *p = "abcd1111abcd2222abcd333qqq";
	ret = strstrCount(p, p2, &count);
	if (ret != 0)
	{
		printf("失败\n");
	}
	printf("OK\n");
	printf("count = %d\n", count);
	system("pause");
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值