设计函数判断一个目标字符串中是否包含模式串(如目标串是”hellloworld”,模式串是”low”, 则包含,如果模式串是”loe”, 则不包含)。
#include "stdio.h"
#include "conio.h"
int getsubstrnum(const char *str1, const char *str2);
int main(void)
{
char str1[50], str2[50];
printf("please input two strings\n");
gets(str1);
gets(str2);
int x=getsubstrnum(str1,str2);
if(x>=1)
printf("包含");
else
printf("不包含");
}
int getsubstrnum(const char *str1, const char *str2)
{
const char *p1 = str1;
const char *p2 = str2;
int sum = 0;
while(*p1 != '\0')
{
if (*p1 == *p2)
{
while(*p1 == *p2 && *p2 != '\0')
{
p1++;
p2++;
}
}
else
p1++;
if (*p2 == '\0')
sum++;
p2 = str2;
}
return sum;
}
#include <conio.h>
#include <stdio.h>
#include<windows.h>
#include <time.h>
#include <string>
#include <algorithm>
using namespace std;
#pragma warning(disable:4996)
#include <iostream>
using namespace std;
bool Contains(const char* src,const char* test) {
bool flag = false;
const char* p = src;
const char* t = test;
while (*p!='\0'&&*t!='\0') {
if (*p == *t) {
t++;
p++;
}
// 如果不相等
else {
if (t != test) {
t = test;
p--;
}
p++;
// continue;
}
}
if (*t == '\0') {
flag = true;
}
return flag;
}
int main(int argc, char** argv)
{
const char* a = "helloworld";
const char* b = "low";
const char* c = "loe";
bool tes = Contains(a, b);
printf("%d", tes);
tes = Contains(a, c);
printf("%d", tes);
}
这个一个一个去匹配就好了。
更绝妙的操作:
bool Contains(const char* p,const char* t) {
bool flag = false;
const char* s = t;
while (*p != '\0' && *t != '\0') {
*p == *t ? t++, p++ : t != s ? t = s : p++;
}
if (*t == '\0') {
flag = true;
}
return flag;
}
int findsubstr(char *str,char *s)
{
int len = strlen(str);
int len1 = strlen(s);
int i,j;
for(i=0;i<len;i++)
{
if(*(str+i) == *s)
{
for(j=1;j<len1;j++)
{
if(*(str+i+j) != *(s+j))
break;
}
if(j==len1) //找到第一个子串
return i;
}
}
return -1;
}
int main()
{
char str[100],s[10];
scanf("%s %s",str,s);
int pos = findsubstr(str,s);
if(pos >= 0)
printf("找到子串,起始位置为:%d",pos);
else
printf("找不到子串");
return 0;
}