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

目录

1.C语言中遍历字符串方式

for循环

while循环

2.strstr函数

练习

初写代码

提交结果

修正代码

提交结果

3.模拟实现strstr


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

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;
	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;
}

提交结果

3.模拟实现strstr

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangcoder

赠人玫瑰手有余香,感谢支持~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值