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