原来的提示是: 编写一个程序来跟踪发言人局。该程序应使用 结构来存储关于说话者的以下数据: 姓名 电话号码 演讲主题 需要费用
程序应使用至少包含 10 个结构的数组。它应该让用户输入 数据放入数组,改变任意元素的内容,显示所有存储的数据 在数组中。该程序应该有一个菜单驱动的用户界面。 输入验证:输入新扬声器的数据时,确保用户输入 所有字段的数据。不得为演讲者费用输入负数。
添加的提示是: 我需要它来扩展搜索模式,其中可能有一个字母或数字拼写错误。只有一个字符可能是错字,在任何位置尝试这些测试模式应该得到以下结果:
0-9 is 0x30-0x39
a-z is 0x41-0x5A
A-Z is 0x61-0x7A (or lower case it)
而且我无法获得添加的提示以使用我当前的程序。
不得更改搜索模式中的其他字符。
#include <iostream>
#include <cstring>
#include<string>
using namespace std;
bool print_one_typo(string input, string people[11], bool is_found[11])
{
bool found = false;
if (input[0] == '?')
{
char *strPtr = NULL;
for (int i = 0; i < 11; i++)
{
strPtr = strstr(people[i].c_str(), input.substr(1).c_str());
if (strPtr != NULL)
{
cout << "\t" << people[i] << endl;
found = true;
is_found[i] = true;
}
}
}
else
{
for (int i = 0; i < 11; i++)
{
bool match = true;
string str = people[i];
int value = str.find(input[0]);
for (int k = 0; k < input.length(); k++)
{
if (input[k] != '?' && input[k] != str[value++])
{
match = false;
break;
}
}
if (match && !is_found[i])
{
found = true;
cout << "\t" << people[i] << endl;
}
}
}
return found;
}
int main()
{
string people[11] = { "Becky Warren, 555-1223",
"Joe Looney, 555-0097",
"Geri Palmer, 555-8787",
"Lynn Presnell, 555-1225",
"Holly Gaddis, 555-8878",
"Sam Wiggins, 555-0998",
"Bob Kain, 555-8712",
"Tim Haynes, 555-7676",
"Warren Gaddis, 555-9037",
"Jean James, 555-9223",
"Ron Palmer, 555-7227" };
bool is_found[11] = { false };
string lookUp;
int i;
cout << "\t People and Phone numbers" << endl;
cout << "Enter name or phone number: ";
cin >> lookUp;
cout << "result: " << endl;
bool found = false;
bool output = false;
for (int i = 0; i < lookUp.length(); i++)
{
string local = lookUp;
found = print_one_typo(local.replace(i, 1, 1, '?'), people, is_found);
if (found) output = true;
}
if (!output)
cout << "No matching product was found" << endl;
return 0;
}
最佳答案
我认为您的代码过度考虑了这个问题。此外,您没有具体说明“拼写错误”是指“错误的字符”,还是更完整的范围,包括删除的字符或插入的字符。
如果您只查找具有零个或一个不正确字符的匹配项,但其他方面长度相同,我认为这段代码应该这样做:
bool print_one_typo(string input, string people[11], bool is_found[11])
{
for (int i = 0; i < 11; i++)
{
if ( is_found[i] ) // Skip if it had already been found?
continue;
if ( input.length() != people[i].length() ) // Are they same length?
continue; // No: Skip it.
int typos = 0;
size_t len = input.length();
for (size_t j = 0; j != len && typos < 2; j++)
if ( input[j] != people[i][j] )
typos++;
if (typos < 2) // Fewer than 2 typos: We have a winner! Return it.
{
is_found[i] = true;
return true;
}
}
return false;
}
此代码会跳过长度不同的字符串,或者您通过 is_found[]
数组过滤掉的字符串。不确定你为什么要这样做,但我保留了你的那部分原始代码。
如果它发现两个长度相同的字符串,它只是逐个字符地比较它们,计算拼写错误。如果它看到 2 个或更多错别字,它会跳到下一个。否则,它采用长度相同但少于 2 个拼写错误的第一个字符串。
关于c++ - 搜索至少 1 个字符时出现错字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17649486/