C++程序:查找字符串中最小和最大的单词
在这个问题中,我们给定一个字符串 str。我们的任务是创建一个C++程序来查找字符串中最小和最大的单词。
问题描述 − 在这里,我们有一个字符串,我们需要找到字符串中所有单词中长度最大和最小的单词。单词由空格或空字符(\0)分隔。
让我们举个例子来理解这个问题
输入
str = “Learn Programming at TutorialsPoint”
输出
smallest word = at largest word = Tutorialspoint
解决方案方法
为了找到最小和最大的单词,我们将使用两个索引来查找每个单词的长度,一个用于单词的开始,另一个用于单词的结束,由空格字符 ' ' 或空字符 '\0' 标记。然后使用开始和结束索引,我们将找到 maxLength 和 minlength。并根据当前单词的长度更新 smallestWord 和 largestWord。
程序说明了我们解决方案的工作原理
示例
#include<iostream>
#include<cstring>
using namespace std;
void minMaxLengthWords(string str){
int StrLength = str.length();
int startIndex = 0, endIndex = 0;
int minLength = StrLength, maxLength = 0, currentLength;
string smallest, largest;
while (endIndex <= StrLength){
if (str[endIndex] != '\0' && str[endIndex] != ' ')
endIndex++;
else{
currentLength = endIndex - startIndex;
if (currentLength < minLength){
smallest = str.substr(startIndex, currentLength);
minLength = currentLength;
}
if (currentLength > maxLength){
largest = str.substr(startIndex, currentLength);
maxLength = currentLength;
}
endIndex++;
startIndex = endIndex;
}
}
cout<<"Smallest Word from the string is "<<smallest<<"\n";
cout<<"Smallest Word from the string is "<<largest;
}
int main() {
string a = "Learn Programming at TutorialsPoint";
minMaxLengthWords(a);
}输出
Smallest Word from the string is at Smallest Word from the string is TutorialsPoint
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP