How to find the longest word in a string with C++

1 Answer

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

std::string longest_word(const std::string& s) {
    std::istringstream iss(s);
    std::string word, max_word;
    std::string::size_type max_size = 0;

    while (iss >> word) {
        if (word.size() > max_size) {
            max_size = word.size();
            max_word = word;
        }
    }
    
    return max_word;
}

int main() {
    std::string s = "C++ is a general purpose programming language created by Bjarne Stroustrup";

    std::string result = longest_word(s);
    std::cout << result;
}



/*
run:

programming

*/

 



answered Sep 16, 2021 by avibootz
edited Mar 2 by avibootz
...