c++ - 在字符串中查找模式
问题描述
我创建了一个名为的方法findPattern
,它将读取一个字符串并检查第一个字符串中是否存在另一个字符串。
前任:
字符串 s1 = "abcdxbc"; 字符串模式=“bc”;
该方法将检查“bc”是否存在string s1
并打印每个出现的模式“bc”的起始索引s1
。
这是调用该方法的方式:
string s1 = "abcdxbc";
string pattern = "bc";
findPattern(string s1,string pattern);
目前,我的方法只能在 1 个字符串中找到模式,但我希望它检查 2 个字符串。
这就是它的名称:findPattern(string s1, string s2, string pattern);
请帮忙
谢谢
findPattern 方法代码:
void findPattern(string s1, string pattern)
{
int s1Len = s1.length();
int pLen = pattern.length();
//for loop to move along the string s1
for (int i = 0; i <= s1Len - pLen; i++)
{
int j = 0;
while(j < pLen && s1[i + j] == pattern[j]) //check that each char in pattern matches the char in s1
{
j++;
}
//if pattern is found inside s1
if(j == pLen) cout << i << " ";
}
}
解决方案
继续您对std::basic_string::find的评论,仅找到第一次出现 - 忽略返回值和size_type pos
作为其第二个参数的参数。要查找所有子字符串,您只需保存返回的字符数并将其加上子字符串的长度一起用作下一个搜索位置,例如
void findPattern (const std::string& s, const std::string& sub)
{
size_t pos = 0,
nchars = 0;
while ((nchars = s.find(sub, pos)) != std::string::npos) { /* find sub */
std::cout << sub << " at: " << nchars << '\n'; /* output result */
pos = nchars + sub.length(); /* update pos */
}
}
"abcdxbc"
将它与为每个字符串和调用函数的循环结合在一起"abcabcb"
,您可以执行以下操作:
#include <iostream>
#include <string>
void findPattern (const std::string& s, const std::string& sub)
{
size_t pos = 0,
nchars = 0;
while ((nchars = s.find(sub, pos)) != std::string::npos) { /* find sub */
std::cout << sub << " at: " << nchars << '\n'; /* output result */
pos = nchars + sub.length(); /* update pos */
}
}
int main (void) {
std::string str[] ={ {"abcdxbc"}, {"abcabcb"} }, /* array of strings */
sub {"bc"}; /* substring to find */
for (auto iter = str; iter != str + 2; iter++) { /* loop over strings */
std::cout << "\nchecking for: '" << sub << "' in '" << *iter << "'\n\n";
findPattern (*iter, sub); /* locate substrings */
}
}
示例使用/输出
$ ./bin/findallsubs
checking for: 'bc' in 'abcdxbc'
bc at: 1
bc at: 5
checking for: 'bc' in 'abcabcb'
bc at: 1
bc at: 4
您可以修改输出以满足您的需求。
所有的std::string.find
, .find_first_of
, .find_first_not_of
, ... 都以相同的方式工作。如果您还有其他问题,请告诉我。
推荐阅读
- android - 移动应用程序是否总是在录制音频时显示?
- java - Volley API 端点
- angular - 角度动态表单以添加顺序显示添加的输入
- javascript - 在 React 中从数组中渲染特定元素
- ruby - 运行要求时“无法加载此类文件 - ruby-debug”表示什么?
- c# - ConnectSsl 方法抛出 System.IO.IOException。现有连接被远程主机强行关闭
- android - 将应用程序从 Google Play 移植到 Amazon FireHD
- java-me - 诺基亚 3310:MIDlet 总是给出“无法编译文件”
- apache-spark - 在 Spark DataFrame 中将列居中的简单方法
- angular - Agm 地图更改建筑物的级别/楼层