How to find the largest and the smallest word in a string with C++

2 Answers

0 votes
#include <iostream>
#include <string>

int main()
{
    std::string s = "cpp c csharp python java";
    std::string word, maxw = "", minw = s;

    for (size_t i = 0; i <= s.length(); i++) {
        if (i < s.length() && s[i] != ' ') {
            word += s[i];
        }
        else {
            if (!word.empty()) {
                if (word.length() < minw.length())
                    minw = word;

                if (word.length() > maxw.length())
                    maxw = word;

                word.clear();
            }
        }
    }

    std::cout << "The largest word is: " << maxw << std::endl;
    std::cout << "The smallest word is: " << minw << std::endl;
}


/*
run:
 
The largest word is: csharp
The smallest word is: c
 
*/

 



answered Mar 21, 2017 by avibootz
edited 1 day ago by avibootz
0 votes
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>

/**
 * Finds the largest and smallest words in a given string.
 * 
 * @param text The input string containing words.
 * @return A std::pair containing (largest_word, smallest_word).
 */
std::pair<std::string, std::string> findLargestAndSmallestWords(const std::string& text) {
    if (text.empty()) {
        return {"", ""};
    }

    // Split the string into words using std::stringstream (similar to Go's strings.Fields)
    std::stringstream ss(text);
    std::vector<std::string> words;
    std::string word;
    while (ss >> word) {
        words.push_back(word);
    }

    if (words.empty()) {
        return {"", ""};
    }

    // Use std::max_element and std::min_element with a custom length-comparison lambda
    auto largestIt = std::max_element(words.begin(), words.end(), 
        [](const std::string& a, const std::string& b) {
            return a.length() < b.length();
        });

    auto smallestIt = std::min_element(words.begin(), words.end(), 
        [](const std::string& a, const std::string& b) {
            return a.length() < b.length();
        });

    return {*largestIt, *smallestIt};
}

int main() {
    std::string s = "C++ is a powerful general-purpose programming language";

    // Use C++17 structured bindings to destructure the returned std::pair cleanly
    auto [largest, smallest] = findLargestAndSmallestWords(s);

    std::cout << "Largest word:  " << largest << '\n';
    std::cout << "Smallest word: " << smallest << '\n';
}


/*
run:
 
Largest word:  general-purpose
Smallest word: a
 
*/

 



answered 1 day ago by avibootz
...