目录
1.C语言中遍历字符串方式
for循环
for (int i=0;i<strlen(arr);i++)
{
cout<<arr[i];
}
while循环
int i=0;
while (arr[i])
{
cout<<arr[i];
i++;
}
2.strstr函数

1.strstr本质上用来查找子字符串,
2.strstr(str1,str2);用来在str1字符串中查找str2第一次出现的位置,如果找到了返回第一次出现的地址;如果没找到返回NULL(空指针)
3.使用前应包含头文件<cstring.h>
练习
https://www.luogu.com.cn/problem/B2118
题目描述
输入两个字符串,验证其中一个串是否为另一个串的子串。
输入格式
两行,每行一个字符串。
输出格式
若第一个串 s1 是第二个串 s2 的子串,则输出
(s1) is substring of (s2);否则,若第二个串 s2 是第一个串 s1 的子串,输出
(s2) is substring of (s1);否则,输出
No substring。输入输出样例
输入 #1
abc dddncabca输出 #1
abc is substring of dddncabca输入 #2
aaa bbb输出 #2
No substring说明/提示
对于 100% 的数据,字符串长度在 20 以内。
初写代码
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char arr1[20];
char arr2[20];
cin>>arr1>>arr2;
if (strstr(arr2,arr1))
cout<<arr1<<" is substring of "<<arr2;
else
cout<<"No substring";
return 0;
}
提交结果

哪里出问题了?
再读一遍题目,验证其中一个串是否为另一个串的子串
即可能arr1是arr2的子串,也可能arr2是arr1的子串,上方代码的if没有判断全
修正代码
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char arr1[20];
char arr2[20];
cin>>arr1>>arr2;
if (strstr(arr2,arr1))
cout<<arr1<<" is substring of "<<arr2;
else if (strstr(arr1,arr2))
cout<<arr2<<" is substring of "<<arr1;
else
cout<<"No substring";
return 0;
}
提交结果

1万+

被折叠的 条评论
为什么被折叠?



