---
title: "C语言判断字符串包含"
author: "yangbinfx"
date: "2018-05-31T19:00:34Z"
tags: []
categories: ["编程语言"]
slug: "c"
draft: false
lastmod: "2018-05-31T18:56:54Z"
id: 2424052
url: "https://yangbinfx.iteye.com/blog/2424052"
---

1\. 使用库函数

string.h   
strstr函数   
函数名: strstr   
功 能: 在串中查找指定字符串的第一次出现   
用 法: char \*strstr(char \*str1, char \*str2); 

                 strchr()                          #对比记忆这是查找字符的。  
说明：返回指向第一次出现str2位置的指针，如果没找到则返回NULL。 

调用函数,判断返回值是否等于NULL,决定是否输出   
如;   
char \*p=".c"; //需要的子串  
if(strstr(A,p)) printf("%s",A);

2\. 不使用库函数

第一行是要查找的字符串   
第二行是被查找句子

输出要查找的字符串在被查找句子的首个位置

#include&lt;stdio.h&gt;  
#include&lt;string.h&gt;  
void main()  
{  
int i,j,la,lb,num=0;  
char c,a\[120],b\[4500];  
while((c=getchar())!='\\n') a\[num++]=c;a\[num]='\\0';  
num=0;  
while((c=getchar())!='\\n') b\[num++]=c;b\[num]='\\0';  
la=strlen(a);lb=strlen(b);  
for(i=0;(lb-i)&gt;=la;i++)  
{if(b\[i]==a\[0])  
{for(j=0;j&lt;la;j++)  
if(b\[i+j]!=a\[j]) break;  
if(j==la) {printf("%d\\n",i+1);break;}  
}  
}  
}

3\. 使用指针

#include "stdio.h"  
#include "conio.h"  
#include "string.h"  
int main()  
{  
char str\[20]="jsdlaadf",substr\[10]="sdf";  
char \*p=str,\*q=substr;  
int flag=0;  
for(;\*(p+strlen(substr)-1);p++)  
{  
for(q=substr;\*p==\*q&&\*q;p++,q++);  
if(!\*q)  
{  
flag=1;  
break;  
}  
}  
if(flag==1) puts("accord");  
else puts("not accord");  
system("pause");  
}