在C ++中查找字符串中最小和最大单词的程序
在本教程中,我们将讨论一个程序来查找字符串中的最小和最大单词。
为此,我们将提供一个字符串。我们的任务是根据长度在字符串中找到最小和最大的单词。
示例
#include<iostream>#include<cstring>
using namespace std;
void minMaxLengthWords(string input, string &minWord, string &maxWord) {
int len = input.length();
int si = 0, ei = 0;
int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0;
while (ei <= len) {
if (ei < len && input[ei] != ' ')
ei++;
else {
int curr_length = ei - si;
if (curr_length < min_length) {
min_length = curr_length;
min_start_index = si;
}
if (curr_length > max_length) {
max_length = curr_length;
max_start_index = si;
}
ei++;
si = ei;
}
}
//存储最小和最大单词
minWord = input.substr(min_start_index, min_length);
maxWord = input.substr(max_start_index, max_length);
}
int main() {
string a = "An apple a day keeps the doctor away";
string minWord, maxWord;
minMaxLengthWords(a, minWord, maxWord);
cout << "Minimum length word: "
<< minWord << endl
<< "Maximum length word: "
<< maxWord << endl;
return 0;
}
输出结果
Minimum length word: aMaximum length word: doctor
以上是 在C ++中查找字符串中最小和最大单词的程序 的全部内容, 来源链接: utcz.com/z/358664.html