用 for 循环和 break 找出以下列表中出现的第一个首字母为"a"的单词,并输出。 wordList = ["cherry", "lemon", "apricot", "blueberry", "durian", "grape", "apple"]
时间: 2023-05-26 09:05:00 浏览: 47
```
wordList = ["cherry", "lemon", "apricot", "blueberry", "durian", "grape", "apple"]
for word in wordList:
if word[0] == "a":
print(word)
break
```
相关问题
用c++输出wordlist中每个单词相关的单词和个数
假设wordlist中存储了一些单词,可以使用哈希表来存储单词及其相关的单词和个数。下面是一个简单的C代码示例:
```c
#include <stdio.h>
#include <string.h>
#define MAX_WORD_LEN 50
#define MAX_WORD_NUM 1000
typedef struct node {
char word[MAX_WORD_LEN];
int count;
struct node *next;
} Node;
Node *hashTable[MAX_WORD_NUM] = {NULL}; // 哈希表
int hash(char *word) {
int sum = 0;
for (int i = 0; i < strlen(word); i++) {
sum += word[i];
}
return sum % MAX_WORD_NUM;
}
void insert(char *word, char *related_word) {
int index = hash(word);
Node *p = hashTable[index];
while (p != NULL) {
if (strcmp(p->word, word) == 0) {
break;
}
p = p->next;
}
if (p == NULL) {
p = (Node *) malloc(sizeof(Node));
strcpy(p->word, word);
p->count = 0;
p->next = hashTable[index];
hashTable[index] = p;
}
p->count++;
Node *q = p;
while (q->next != NULL) {
if (strcmp(q->word, related_word) == 0) {
return;
}
q = q->next;
}
Node *r = (Node *) malloc(sizeof(Node));
strcpy(r->word, related_word);
r->count = 1;
r->next = NULL;
q->next = r;
}
void output() {
for (int i = 0; i < MAX_WORD_NUM; i++) {
Node *p = hashTable[i];
while (p != NULL) {
printf("%s: %d\n", p->word, p->count);
Node *q = p->next;
while (q != NULL) {
printf("- %s: %d\n", q->word, q->count);
q = q->next;
}
p = p->next;
}
}
}
int main() {
char word[MAX_WORD_LEN], related_word[MAX_WORD_LEN];
while (scanf("%s %s", word, related_word) != EOF) {
insert(word, related_word);
insert(related_word, word);
}
output();
return 0;
}
```
在输入阶段,对于每个单词及其相关的单词,调用insert函数插入哈希表中。在insert函数中,先查找哈希表中是否已经存在该单词的节点,如果不存在,则创建一个新节点,并将其插入哈希表中。然后遍历该单词节点的相关单词链表,如果已经存在相关单词,则不做处理,否则创建一个新节点,并将其插入相关单词链表中。
最后调用output函数输出每个单词及其相关的单词和个数。
java编写一个程序,对一个字符串中的所有单词进行计数,并按照出现次数从大到小排序输出。
好的,以下是一个基于HashMap实现的Java程序:
```java
import java.util.*;
public class WordCount {
public static void main(String[] args) {
String str = "hello world hello java world java world";
String[] words = str.split("\\s+");
Map<String, Integer> wordCount = new HashMap<>();
// 统计每个单词出现的次数
for (String word : words) {
if (wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
} else {
wordCount.put(word, 1);
}
}
// 将单词按照出现次数从大到小排序
List<Map.Entry<String, Integer>> wordList = new ArrayList<>(wordCount.entrySet());
Collections.sort(wordList, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
// 输出结果
for (Map.Entry<String, Integer> entry : wordList) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
```
假设输入的字符串为:"hello world hello java world java world",输出结果为:
```
world : 3
hello : 2
java : 2
```