题目链接:
解题思路:
本质上也是要用双层循环,
最外层循环要遍历输入的字符串中的每一个字符,即 while (*s)
遍历期间的每一个字符都要拿来和要统计字串个数的字串作比较,
这其中的比较就要在内层循环中进行,
其比较的次数要依据子串的个数而定,
即 *(s + j)是否等于 *(son + j)
其中的 j 的最大值便是子串的个数
参考代码:
#include<bits/stdc++.h>
using namespace std;
int func(char *s,char *son)
{
int num = 0;
//for(int i = 0;i < strlen(s);i++)不要采用该种外层循环
while(*s)
{
for(int j = 0;j < strlen(son);j++)
{
if(*(s+j) != *(son+j))//这样可以保证俩个字符串同时进行比较
{
break;
}
if(j == strlen(son)-1)//比较结束没有提前退出并且是字符串的一个字串
{
num++;
}
}
s++;
}
return num;
}
int main( )
{
char s[100];
cin.getline(s,100);//不要忘了前面的 cin.
char son[100];
cin.getline(son,100);
int end = func(s,son);
cout << end;
return 0;
}
变式训练:
题目链接:
参考代码:
#include<bits/stdc++.h>
using namespace std;
int main( )
{
char s[100] = " ";
//字符数组尽量用“”进行初始化,因为它会自动在末尾添加字符串的结束标志、0
cin.getline(s,100);
char *cur = s;
int max = 0;
while(*cur)
{
int num = 2;
char *tmp = cur+1;//外层循环所遍历到字符的下一个字符
if(*tmp == *cur)//遍历到的字符与其下一个字符相等的情况
{
while(*(tmp) == *(tmp+1))
{
tmp++;
num++;//根据if语句的条件,则这里num的初始值必须为2
}
if(max < num)
{
max = num;
}
}
else
{
num = 1;//为了应对有 1234 这种情况的发生
}
cur++;
}
cout << max;
return 0;
}