查找字符串匹配并输出位置
Finding String Match and output the position
我对编程非常陌生,所以这是一个非常"混乱"/"无聊"的代码。
情况是,如果我有两个字符串
例如
ASDFHJKL和PFUYASD
我想输出他们的位置,字母匹配如下:
"在1号股的0和2号股的6处发现匹配"
条件:
- 它们必须最多匹配三个并排的字符。(示例中未考虑F的原因)
- 股1比股2长
所以我得到了这个代码,它可以查找第二个字母的匹配项。这很好
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
int x = 0;
int y = 0;
int str1match;
int str2match;
string str1;
string str2;
cout << "string1n";
cin >> str1;
cout << "string2n";
cin >> str2;
int length = str1.length();
startagain:
int pos = str2.find(str1[x]);
if ((pos >= 0) && (x<length))
{
x = x + 1;
pos = pos + 1;
if (str1[x] == str2[pos])
{
x = x + 1;
pos = pos + 1;
if (str1[x] == str2[pos])
{
str1match = x - 2;
str2match = pos - 2;
cout << "Match at " << str1match << " of Strand 1 and at " << str2match << " of Strand 2";
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else if ((pos == -1) && (x<length))
{
x = x + 1;
goto startagain;
}
else
{
cout << "Match not found";
}
_getch();
return 0;
}
但我需要代码来找到匹配,直到至少第三个字母,所以我认为只要添加更多的嵌套循环就可以了,但事实并非如此。这是不起作用的代码:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
int x = 0;
int str1match, str2match;
string strand1, strand2;
cout << "Enter Strand 1:n";
cin >> strand1;
cout << "Enter Strand 2:n";
cin >> strand2;
int length = strand1.length();
startagain:
int pos = strand2.find(strand1[x]);
if ((pos >= 0) && (x < length))
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
str1match = x - 3;
str2match = pos - 3;
cout << "Match at " << str1match << "of Strand 1 and at " << str2match << "of Strand 2";
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else if ((pos == -1) && (x < length))
{
x = x + 1;
goto startagain;
}
else
{
cout << "Match not found";
}
_getch();
return 0;
}
bool found = false;
for(int i=0;i<strand1.size()-2;i++){
int pos = strand2.find(strand1.substr(i,3));
if(pos != string::npos){
found = true;
cout << "match at " << i << "in 1 with " << pos << " in 2" << 'n';
break;
}
}
if (!found) cout << "No match";
string.substr查找从i 开始的子字符串
相关文章:
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 如何选择在 csv 文件中输出的位置
- 流中的输入位置和输出位置有什么区别?
- 如何更改输出的位置或光标在输出处,以便在"Code Blocks"中C++
- 来自不同位置的数组输出的执行时间
- 填写C 程序中缺少的位置以获取所需的输出
- 更新:正在输出内存位置,而不是所需的字符串
- 指针在字符串C 中的输出位置
- 排序为最后一个位置的元素提供错误的输出
- 输出文本文件的位置
- 二进制输出到C++中随机位置的文件
- 读取并输出二进制文件(C++)中位置的字节
- strlen()的奇怪行为,当在代码中的不同位置使用时,会给出不同的输出
- 使用 .tellg() 的输出来了解文件中的位置
- 面向对象C++帮助?出于某种原因,对象变量的输出返回数值数组位置而不是实际值
- 集成瓦尔格林德输出以找出数据竞赛的位置
- 构建一个程序,将 10 个整数放入数组中并识别重复的数字并输出它们及其位置编号的位置
- 查找字符串匹配并输出位置
- c++文件IO,如何指定输出位置
- Valgrind输出位置不正确