【发布时间】:2020-11-12 13:28:16
【问题描述】:
我想实现一个 C/C++ 函数,它的输入是一个字符数组,像这样:
char string[]="abccccfffcccccc"
然后搜索特定的字符串模式,然后根据我搜索到的模式的最后一个索引+6个字符返回一个字符数组(字符串)。
例如,假设我要搜索字符串模式"ab",因此如果在我的输入中找到搜索的模式,则返回从我搜索的模式的最后一个索引开始并结束于 ( index + 6),因此在这种情况下,返回的子字符串将为"ccccff",因为"ab" 的最后一个索引位于index=1,因此返回的子字符串将从索引2 开始(下一个索引为1+1 = > 在索引 2 处),子字符串的结尾将在索引 1 + 6=7 处结束(从索引 1 移动 6 个字符)。
我在代码中所做的是:
#include <string>
using namespace std;
int main(){
string str1 = "abccccfffcccccc"; // this example just for finding out if my function gives me the first index of every the specific pattern appearance
string str2 = "ab"; %pattern that I'm searching in the given string-str1.
int pos = 0;
int index;
while ((index = strstr(str1,str2)) != NULL){
cout << "Match found at position: " << index << endl;
cout << "Required String starts from index + 1 until the end is " << str1[str1.length()-(index)]; // % in my case it outputs and print "ccccff" because the first index of 11 is index=zero so the string should starts from index+1
pos = index + 1; //new position is from next element of index
}
return 0;
}
我得到了错误的输出。谁能帮我用 C 或 C++ 实现这个?
我在给定字符串中搜索的子字符串可能出现多次。这意味着,例如,在给定的字符串"abccccfffccabcc" 中,如果我搜索子字符串"ab",我需要为"ab" 的每次出现返回所需的输出,如上所述(假设数组的大小与我的问题兼容,并且没有超出索引错误等)。
另外,如果我搜索的子字符串不包含在给定的字符串中,则返回NULL。
【问题讨论】:
-
所以用
000ab111ab222搜索ab你想得到['000ab', '111ab']? -
@Berto99 根据 OP 的描述和尝试的代码,它需要改为
['111ab2'],或者可能是['111ab2', '222']
标签: c++ arrays c string algorithm