c++ - 控制一个字符串是否存在于另一个字符串中(在 C++ 中)
问题描述
如何确定给定字符串是否完全包含另一个子字符串?
我可以使用的库和函数不受限制,我只需要最简单的解决方案即可。
带有一些输入的示例:
string str1 = "helloworld"; //master string
string str2 = "low"; //substring
std::cout << contains(str1, str2); //should print True, "low" is in "helloworld"
string str1 = "hello-world"; //master string
string str2 = "low"; //substring
std::cout << contains(str1, str2); //should print False, "low" is NOT present in "hello-world"
解决方案
#include <iostream>
#include <string.h>
using namespace std;
bool contains(char *sub, char *whole);
int main(void)
{
char sub[] = "hello";
char sub2[] = "hey";
char whole[]= "well hello world";
if(contains(sub, whole))
cout << "it does" << endl;
else
cout << "it does not" << endl;
if(contains(sub2, whole))
cout << "it does" << endl;
else
cout << "it does not" << endl;
return 0;
}
bool contains(char *sub, char *whole)
{
for(int i=0 ; i<strlen(whole) ; i++)
{
bool match=true;
for(int j=0 ; j<strlen(sub) ; j++)
{
if(sub[j] != whole[j+i])
match = false;
}
if(match)
return true;
}
return false;
}
推荐阅读
- ruby-on-rails - Vue.js 和 Rails:如何在 Vue 之前阻止 HTML 渲染?
- javascript - 从减速器的视图中调用方法
- python - 在具有相似但不精确值的列上加入数据框
- python - 使用 BeautifulSoup 从一行中提取某些值
- node.js - Google App Engine Deploy 服务帐户适用于一项服务,但不是相同的服务
- python - 如果 timezone 不是 None,则 Datetime "fromtimestamp()" 忽略继承
- python - 插入空格以分隔连接的字母和数字字符串 - Python RegEx
- html - Hugo 不在子目录 [File.Dir] 中显示页面
- javascript - 您如何等待过滤器循环的每次迭代而不是整个循环的完成?
- c# - UWP 应用程序声称它在发布构建期间引用了自己的 exe -“清单引用文件”,它不是有效负载的一部分“