搜索以特定字母开头的名称的所有匹配项
searches for all occurrences of a name that begins with a specific letter
>编写一个函数 searchName,用于搜索以特定字母开头的名称的所有匹配项。 将下标存储在名为 searchResults 的数组中,该数组最多存储 20 个元素,然后在屏幕上显示列表。
以下是名称列表:
约翰·玛丽·山姆·汤姆·丽莎·特蕾莎·彼得·哈里斯·玛西亚·约翰·劳伦斯·阿明·杰弗里·玛丽亚·阿强·菲拉·克拉克·佩德罗·杰米·凯文·
我的代码:
void searchName(string n[], int lsize){
int searchcount = 0;
if(searchString[0] == n[i][0]){
searchResults[searchcount] = 1;
}
#include <iostream>
using namespace std;
//an index used to properly store new letters in an array
int nextPosition;
//the maximum length the array can be
const int LIST_LENGTH = 20;
//an array to store unique letters
char searchResults[LIST_LENGTH];
//an array to store each letters count
int searchCount[LIST_LENGTH];
// Note: because ^these variables are defined
// outside any function they can be used anywhere in the file
void searchName(string name) {
//a 'flag' is used to tell if an entry for a letter has been recorded
bool noEntryFound = true;
//search unique letters for a match
for (int j = 0; j < nextPosition; j++){
//if the letter has been added already, increment it
if ( searchResults[j] == name[0] ){
searchCount[j] += 1;
//found an entry, so this flag is alternated,
// stopping more than 1 entry for the letter being added to array
noEntryFound = false;
//first letter is already in the array so breaking
// the loop saves searching the rest of the array
break;
}
}
//if the array has been searched
//and the letter wasn't found, add it, increment it
if (noEntryFound == true){
//store new letter, increment its count
searchResults[nextPosition] = name[0];
searchCount[nextPosition] += 1;
//increment the position that new items get added to the array at
nextPosition++;
}
}
int main(){
//the array of names of length 20 (LENGTH)
string names[LIST_LENGTH] = {
"John P.", "Mary Q.", "Sam T.",
"Tom L.","Lisa O.", "Teresa A.",
"Peter B.", "Harris W.", "Marcia D.",
"John G.", "Lawrence F.", "Amin C.","Jeffrey N.",
"Maria Z.", "Cuong N.","Fila H.", "Clark R.",
"Pedro J.","Jamie O.", "Kevin Y."
};
//iterate over all names as input for searchName
for (int i=0; i < LIST_LENGTH; i++){
searchName(names[i]);
}
//finally, print each letter and its equivalent count
for (int k=0; k<nextPosition; k++){
cout << searchResults[k] << " : " << searchCount[k] << endl;
}
return 1;
}
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 在C++中搜索嵌套多映射值
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- 正在尝试重载二进制搜索树分配运算符
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 向量上的线性搜索
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 如何在动态数组上使用搜索函数
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- cmake:添加要搜索头文件的目录
- 使用C++创建特殊的二叉搜索树
- 在C++的字符串中搜索和删除某些字符
- std::unordered_map 搜索算法是如何实现的?
- 使用不变量来确定二分搜索中的边界条件
- 二叉搜索如何比线性搜索更快?
- 按边长度递归搜索图中所有可行路径
- 搜索以特定字母开头的名称的所有匹配项
- 为什么 TrimRight 从字符串的开头搜索