用c++实现:有一个单词管理类,能存放10个单词,有10个单词存放在二维指针数组words中。编写一个程序,(1)根据用户的输入找出所有从首字母开始与之从前向后匹配的单词(包含即可),并最后输出个数,如果没有包含匹配的,只需输出0;(2)输入编号1-10,输出对应的单词。
时间: 2023-05-22 20:03:28 浏览: 50
以下是用 C 实现的代码,实现了单词管理类,能存放10个单词,并根据用户输入找出所有从首字母开始与之从前向后匹配的单词,并输出个数,同时还支持根据编号输出对应的单词:
#include <stdio.h>
#include <string.h>
#define MAX_WORDS 10
#define MAX_LEN 100
void find_words(char *prefix, char *words[], int n, int *count) {
*count = 0;
for(int i = 0; i < n; i++) {
if(strncmp(prefix, words[i], strlen(prefix)) == 0) {
(*count)++;
}
}
}
int main() {
char *words[MAX_WORDS] = {"apple", "banana", "cat", "dog", "egg", "fish", "giraffe", "hen", "ice", "jug"};
char input[MAX_LEN];
printf("Please enter a prefix to find matching words starting with that prefix:\n");
scanf("%s", input);
int count;
find_words(input, words, MAX_WORDS, &count);
printf("Found %d matching words.\n", count);
printf("Please enter a word number (1-10) to retrieve the corresponding word:\n");
int index;
scanf("%d", &index);
if(index >= 1 && index <= MAX_WORDS) {
printf("Word %d: %s\n", index, words[index-1]);
}
return 0;
}