我正在尝试创建一种名为recombine
的方法,该方法将3个字符串s1
,s2
和s3
作为输入。此方法将使用以下格式的s1
重新组合字符串s2
和s3
:string s1Prime = s1_Left + s3 + s2_Right;
// s1Prime是重组后的s1string s2Prime = s2_Left + s3 + s1_Right;
// s2Prime是重组后的s2
重组方法代码
void recombine(string s1, string s2, string s3)
{
int s1PatternIndex = s1.find(s3);
int s2PatternIndex = s2.find(s3);
string s1_Left = s1.substr(0,s1PatternIndex); //stores all of ```s1``` characters that are to the left of ```s3```
string s1_Right = s1.substr(s1PatternIndex + s3.length(), s1.length()); //stores all of ```s1``` characters that are to the right of ```s3```
string s2_Left = s2.substr(0,s2PatternIndex); //stores all of ```s2``` characters that are to the left of ```s3```
string s2_Right = s2.substr(s2PatternIndex + s3.length(), s2.length()); //stores all of ```s2``` characters that are to the right of ```s3```
string s1Prime = s1_Left + s3 + s2_Right; //```s1``` after recombination
string s2Prime = s2_Left + s3 + s1_Right; //```s2``` after recombination
cout << s1Prime << endl;
cout << s2Prime << endl;
}
测试重组方法string s1 = "AGCGADA";
string s2 = "ATTGCG";
string s3 = "GC";
recombine(s1,s2,s3);
//Console output:
// s1Prime: AGCG
// s2Prime: ATTGCGADA
我的当前方法仅在s3
仅在s1和s2中仅发生一次的情况下才有效,但是我试图使其重新组合超过1次。例如:
如果s1 =“AGCGAGCA”和s2 =“TAGCTTGCGAT”并且s3 =“GC”
在此示例中,
s3
在s1
中存在两次,在s2
中两次,因此将有4种不同的可能性和八种不同的重组方式(s1
4种,s2
4种)4种不同的可能性是:
s3
中的s1
第一次出现和s3
中的s2
第一次出现s3
中的s1
的第1次出现和s3
中的s2
的第2次出现为例s3
中第二次出现s1
,在s3
中第一次出现s2
s3
中第二次出现s1
和在s3
中第二次出现s2
请在我的代码中建议如何实现。
最佳答案
给定像AGCGAGCA
这样的字符串,您可以做的是编写一个返回字符串对的函数。每对是匹配的特定样式的图案的左侧和右侧,例如
AGCGAGCA with pattern GC
gives
{AG, AGCA}
{AGCGA, A}
功能如下:auto lefts_and_rights(std::string_view input, std::string_view pattern)
{
std::vector<std::pair<std::string_view, std::string_view>> res;
auto pos = std::string::npos;
while((pos = input.find(pattern, pos + 1)) != std::string::npos)
res.push_back(std::make_pair(input.substr(0, pos),
input.substr(pos + pattern.length())));
return res;
}
现在,您可以像这样方便地编写recombine
:void recombine(std::string_view s1, std::string_view s2, std::string_view s3)
{
for (auto [left_s1, right_s1] : lefts_and_rights(s1, s3))
for (auto [left_s2, right_s2] : lefts_and_rights(s2, s3))
{
std::cout << left_s1 << s3 << right_s1 << "\n";
std::cout << left_s2 << s3 << right_s2 << "\n";
}
}
这是demo。
关于c++ - 根据模式的出现重新组合字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64546365/