最长最短单词

这篇博客探讨了如何在给定的文本中找到最长和最短的单词。通过解析内容,我们可以看到作者使用了不同的算法和数据结构来高效地解决这个问题,包括字符串操作、分词和排序。博客还可能涵盖了性能优化和错误处理的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <vector>
#include <string>
using namespace std;
 
int main() 
{
	vector<string> vecwords;
	char chin='1';
 
	string strword;
	while(1)
	{
		chin=getchar();
		if(chin=='\n')
		{
			vecwords.push_back(strword);
			break;
		}
		else if(chin!=','&&chin!=' ')
		{
			string strc(1,chin);
			strword+=strc;
		}
		else
		{
			vecwords.push_back(strword);
			strword="";
		}
	}
	
	int ishortpos=0,ishortlen=vecwords[0].length();
	int ilongpos=0,ilonglen=vecwords[0].length();
	for(int i=1;i<vecwords.size();i++)
	{
		if(vecwords[i].length()==0) 
			continue;
		if(vecwords[i].length()<ishortlen)
	
### 使用 Java 查找字符串中最长单词 为了实现这一功能,可以通过读取输入字符串并将其分割成单独的单词来完成。之后,通过遍历这些单词以确定哪个是最长的,哪个是的。 下面是一个简单的例子,展示了如何使用 Java 来查找给定字符串中长度大和小的单词[^3]: ```java import java.util.ArrayList; import java.util.List; public class FindMinMaxWords { public static void main(String[] args) { String input = "hello world from the other side"; List<String> shortestWords = new ArrayList<>(); List<String> longestWords = new ArrayList<>(); findShortestAndLongestWords(input, shortestWords, longestWords); System.out.println("Shortest word(s): " + shortestWords); System.out.println("Longest word(s): " + longestWords); } private static void findShortestAndLongestWords(String sentence, List<String> shortestWords, List<String> longestWords){ String[] words = sentence.split("\\s+"); int minLength = Integer.MAX_VALUE; int maxLength = 0; for (String word : words) { int length = word.length(); if(length < minLength){ minLength = length; shortestWords.clear(); // 清空列表以便重新填充新的词 shortestWords.add(word); }else if(length == minLength){ shortestWords.add(word); } if(length > maxLength){ maxLength = length; longestWords.clear(); // 同样清空列表用于更新最长词 longestWords.add(word); }else if(length == maxLength){ longestWords.add(word); } } } } ``` 此程序首先定义了一个辅助函数 `findShortestAndLongestWords` ,它接收一个句子作为参数,并返回两个列表分别保存最长的词语。对于每个遇到的新单词,都会检查其长度是否小于当前记录下的小长度或是大于大长度;如果是,则相应地更新这两个变量以及对应的存储列表。当存在多个具有相同极值长度的不同单词时,它们都将被加入到相应的集合之中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

读万卷书不如行万里路呀

您的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值