前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C语言之strstr函数

C语言之strstr函数

作者头像
全栈程序员站长
发布2022-09-12 17:55:25
3370
发布2022-09-12 17:55:25
举报

大家好,又见面了,我是你们的朋友全栈君。

【FROM MSDN && 百科】

原型:char *strstr(const char *str1, const char *str2);

#include<string.h>

找出str2字符串在str1字符串中第一次出现的位置(不包括str2的串结束符)。返回该位置的指针,如找不到,返回空指针。

Returns a pointer to the first occurrence of strSearch in str, or NULL if strSearch does not appear in str. If strSearch points to a string of zero length, the function returns str.

DEMO: mystrstr

代码语言:javascript
复制
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#pragma warning (disable:4996)
char *mystrstr(char *s1,char *s2);
int main(void)
{
	char *s="Golden Global View";
	char *l="ob";   //char *l=""
	char *p;
	system("cls");
	p=mystrstr(s,l);
	if (p!=NULL)
	{
		printf("%s\n",p);
	}
	else
	{
		printf("Not Found!\n");
	}
    getch();
	return 0;
}
/*FROM 百科*/
char *mystrstr(char *s1,char *s2)
{
	int n;
	if (*s2)                      //两种情况考虑
	{
        while(*s1)               
		{
            for (n=0;*(s1+n)==*(s2+n);n++)
            {
				if (!*(s2+n+1))            //查找的下一个字符是否为'\0'
				{
					return (char*)s1;
				}
            }
			s1++;
		}
		return NULL;
	}
	else
	{
		return (char*)s1;
	}
}

DEMO:

代码语言:javascript
复制
//#define FIRST_DEMO
#define SECOND_DEMO

#ifdef FIRST_DEMO
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main(void)
{
	char *s="Golden Global View";
	char *l="lob";
	char *p;
	system("cls");
	p=strstr(s,l);
	if (p!=NULL)
	{
		printf("%s\n",p);
	}
	else
	{
		printf("Not Found!\n");
	}

	getch();
	return 0;
}
#elif defined SECOND_DEMO
/*从字串” string1 onexxx string2 oneyyy”中寻找”yyy”*/
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main(void)
{
	char *s="string1 onexxx string2 oneyyy";
	char *p;
	p=strstr(s,"string2");
	printf("%s\n",p);
	if (p==NULL)
	{
		printf("Not Found!\n");
	}
	p=strstr(p,"one");
	printf("%s\n",p);
	if (p==NULL)
	{
		printf("Not Found!\n");
	}
	p+=strlen("one");
	printf("%s\n",p);

	getch();
	return 0;
}
#endif

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/153025.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档