输入两个字符串s1和s2,在s1中查找s2对应的字符串是否存在,若存在则输出它的第一次出现的位置;若不存在,则输出“没有找到该字符串”。
C++代码如下:如有帮助,请采纳一下,谢谢。
#include <iostream>
#include <string>
using namespace std;
//查找big串中所有smal串的位置,并把位置存放在pos中,nmb存放个数
void findstr(const char*big ,const char* smal,int pos[],int *nmb)
{
int i,j,lenb,lens;
lenb = strlen(big);
lens = strlen(smal);
*nmb = 0;
if(lens > lenb)
return;
i = 0;
while(i < lenb-lens+1)
{
for (j = 0; j < lens;j++)
{
if(tolower(big[i+j]) != tolower(smal[j]))
break;
}
if (j == lens) //说明找到
{
pos[*nmb] = i;
(*nmb)++;
i += lens;
}else
i++;
}
}
int main()
{
string s1 = "";
string s2 = "";
int pos[10];
int nmb = 0;
cout << "请输入两个字符串" << endl;
cin >> s1;
cin >> s2;
findstr(s1.c_str(),s2.c_str(),pos,&nmb);
if (nmb <= 0)
{
cout << "没有找到该字符串" << endl;
}else
cout << "第一个位置:" << pos[0];
return 0;
}
C代码如下
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//查找big串中所有smal串的位置,并把位置存放在pos中,nmb存放个数
void findstr(char big[] ,char smal[],int pos[],int *nmb)
{
int i,j,lenb,lens;
lenb = strlen(big);
lens = strlen(smal);
*nmb = 0;
if(lens > lenb)
return;
i = 0;
while(i < lenb-lens+1)
{
for (j = 0; j < lens;j++)
{
if(tolower(big[i+j]) != tolower(smal[j]))
break;
}
if (j == lens) //说明找到
{
pos[*nmb] = i;
(*nmb)++;
i += lens;
}else
i++;
}
}
int main()
{
char s1[100] ={0};
char s2[100] = {0};
int pos[10];
int nmb = 0;
printf("请输入两个字符串\n");
gets(s1);
gets(s2);
findstr(s1,s2,pos,&nmb);
if (nmb <= 0)
{
printf("没有找到该字符串\n");
}else
printf("第一个位置:%d\n",pos[0]);
return 0;
}