欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > C11.【C++ Cont】遍历字符串的两种方式和strstr函数

C11.【C++ Cont】遍历字符串的两种方式和strstr函数

2025/4/20 13:44:04 来源:https://blog.csdn.net/2401_85828611/article/details/144798989  浏览:    关键词:C11.【C++ Cont】遍历字符串的两种方式和strstr函数

目录

1.遍历字符串的两种方式

for循环

while循环

2.strstr函数

练习

初写代码

提交结果

修正代码

提交结果

3.模拟实现strstr


1.遍历字符串的两种方式

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函数

cplusplus网的介绍 点我跳转

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;elsecout<<"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;elsecout<<"No substring";return 0;
}

提交结果

3.模拟实现strstr

具体参见55.【C语言】字符函数和字符串函数(strstr函数)文章

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词