搜索以特定字母开头的名称的所有匹配项

searches for all occurrences of a name that begins with a specific letter

本文关键字:搜索 开头      更新时间:2023-10-16

>编写一个函数 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;
}