编程实现在单词表中查找与已知单词最接近的单词:
(1) 如果单词表中有要查找的单词输出该单词的位置;
(2) 如果单词表中没有要查找的单词,输出与要查找的单词最接近的单词。最接近的单词是指: 两个单词仅有一个字母不同,如:hello和hallo。
#include<iostream> #include<string> using namespace std; int main() { string wl = "he jkp abc rty"; //假定wl为单词表 //getline(cin,wl); cout << "--------" << endl; cout << wl; cout << "--------" << endl; string s; cin >> s; //s为待查单词 int i = 0, j = 0; int locate = 0; //locate为每个单词的起始位置 int sum = 0; //统计不同字母的个数 int num = 0; //当前单词长度 while (j < wl.size()) { if (s[i] == wl[j]) { i++; j++; num++; } else { sum++; i++; j++; num++; } if (sum > 1) {
//跳到下一个单词 i = 0; sum = 0; num = 0; while (j < wl.size()) { if (wl[j] == ‘ ‘) { locate = j + 1; j++; break; } j++; } } if ((sum == 1) && (num == s.size())) break; if(sum==0 && (num == s.size())) break; } if (sum == 1){ for (int j = locate;j < wl.size();j++) { if (wl[j] == ‘ ‘) break; cout << wl[j]; } } if(sum==0) cout<<locate; return 0; }
原文:https://www.cnblogs.com/sqm724/p/12739134.html