在本教程中,我们将讨论一个程序来查找字符串中的最小和最大单词。
为此,我们将提供一个字符串。我们的任务是根据长度在字符串中找到最小和最大的单词。
#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: a Maximum length word: doctor