用c语言实现:处理事先不知道单词总数量的字符串,从中随机选择一个单词,并打印总单词数以及该单词是第几个
时间: 2024-05-08 12:22:34 浏览: 11
以下是用 C 语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_LEN 1000
int main() {
char str[MAX_LEN];
char *word;
int total_words = 0;
int word_count = 0;
int i;
printf("Please enter a string: ");
fgets(str, MAX_LEN, stdin);
// count number of words
for (i = 0; i < strlen(str); i++) {
if (str[i] == ' ' || str[i] == '\n') {
total_words++;
}
}
// randomly select a word
srand(time(NULL)); // seed for random number generator
int random_index = rand() % total_words + 1; // random number between 1 and total_words
word = strtok(str, " \n");
for (i = 1; i < random_index; i++) {
word = strtok(NULL, " \n");
}
// count number of words before selected word
for (i = 0; i < strlen(str); i++) {
if (str[i] == ' ' || str[i] == '\n') {
word_count++;
if (str + i + 1 == word) {
break;
}
}
}
printf("Total words: %d\n", total_words);
printf("Selected word: %s\n", word);
printf("Word count: %d\n", word_count);
return 0;
}
```
代码的主要思路是先遍历字符串,计算出总共有多少个单词,然后使用随机数生成器随机选择一个单词,并打印出总单词数和该单词是第几个单词。其中,使用 `strtok` 函数将字符串分割成单词,然后使用计数器统计单词的数量。注意,由于 `strtok` 函数是有状态的,因此需要在第一次调用时传入原字符串,后续调用时传入 `NULL`。