1140:验证子串

1140:验证子串

时间限制: 1000 ms 内存限制: 65536 KB
提交数: 23641 通过数: 11420
【题目描述】
输入两个字符串,验证其中一个串是否为另一个串的子串。

【输入】
输入两个字符串, 每个字符串占一行,长度不超过200且不含空格。

【输出】
若第一个串s1是第二个串s2的子串,则输出(s1) is substring of (s2)

否则,若第二个串s2是第一个串s1的子串,输出(s2) is substring of (s1)

否则,输出 No substring。

【输入样例】
abc
dddncabca
【输出样例】
abc is substring of dddncabca

代码如下:

#include<bits/stdc++.h>
using namespace std;
int main()
{
	char s1[200],s2[200];
	
	gets(s1);
	gets(s2);
	
	if(strstr(s2,s1))
	{
		cout<<s1<<" is substring of "<<s2<<endl;
		return 0; 
	}
	if(strstr(s1,s2))
	{
		cout<<s2<<" is substring of "<<s1<<endl;
		return 0;
	}
	cout<<"No substring"<<endl;
	return 0;
}
### 关于 `substr()` 函数用于查询子串的用法 `substr()` 并不是一个专门用来查找子串的函数,它的主要功能是从字符串中提取一段子串。然而,在实际开发中,它通常会与 `find()` 或其他类似的查找函数一起使用,从而实现更复杂的操作。 #### 配合 `find()` 使用的例子 当需要定位某个子串的位置并从中提取部分数据时,可以先利用 `find()` 找到该子串的起始位置,再调用 `substr()` 提取所需的片段。以下是具体示例: ```cpp #include <iostream> #include <string> using namespace std; int main() { string s = "hello world hello everyone"; size_t n = s.find("world"); // 查找子串"world"的起始位置 if (n != string::npos) { // 如果找到了子串 string extractedSubstring = s.substr(n, 10); // 从找到的位置开始提取10个字符 cout << extractedSubstring << endl; // 输出: "world hell" } return 0; } ``` 上述代码展示了如何结合 `find()` 和 `substr()` 来完成特定任务[^1]。其中,`find()` 返回的是子串 `"world"` 的起始索引,而 `substr(size_t pos, size_t len)` 则允许指定从哪个位置开始以及要截取多少个字符。 #### 单独使用 `substr()` 的情况 即使没有预先知道确切的目标范围,也可以仅依靠 `substr()` 自身的功能来进行一些基本的操作。比如下面这个例子说明了如果不提供第二个参数(表示长度),那么默认情况下将会一直拷贝直到原字符串结束为止: ```cpp #include <iostream> #include <string> using namespace std; int main(){ string str1("Heterological paradoxes are persistent."); cout<<"The original string str1 is:"<<endl; cout<<str1<<endl; basic_string<char>str2=str1.substr(6,7); cout<<"The substring str1 copied is:"<<str2<<endl; basic_string<char>str3=str1.substr(); cout<<"The default substring str3 is:"<<endl; cout<<str3<<endl; cout<<"which is the entire original string."<<endl; return 0; } ``` 这段程序演示了两种不同的方式来创建新的子串对象:一种是指定明确的起点和终点;另一种则是简单地复制整个原始字符串的内容[^4]。 尽管如此,请注意虽然我们可以借助像 C++ 中这样的组合方法间接达到目的,但在 JavaScript 这样的语言里则有更加直接的方法去验证某段文字内部是否存在给定模式——那就是运用内置的 `indexOf()` 方法[^3]: ```javascript const str = 'Hello, world!'; const substr = 'world'; const index = str.indexOf(substr); if (index >= 0){ console.log('字符串包含子串'); } else{ console.log('字符串不包含子串'); } ``` 这里展示了一个简单的条件分支结构,通过比较由 `indexOf()` 得来的数值是否满足非负的要求,进而得出结论关于输入句子里是否有待寻找的部分[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值