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

1 Answer

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

std::string find_second_largest_word_in_string(std::string str) {
    std::string second_largest = "", largest = "";
    int found_second = 0;
    
    std::stringstream iss(str);
    std::string word;  
    while (iss >> word) {
         if (word.length() > largest.length()) {
            second_largest = largest;
            largest = word;
        }
        else if (word.length() > second_largest.length() && !found_second) {
            second_largest = word;
            found_second = 1;
        }
    }
    
    return second_largest;
}

int main() {
    std::string str = "c cpp cobol c# python java";

    std::cout << "The second largest word is: " << find_second_largest_word_in_string(str);
}

 
 
/*
run:
 
The second largest word is: cobol

*/

 



answered Jun 2, 2024 by avibootz

Related questions

1 answer 114 views
1 answer 101 views
1 answer 95 views
1 answer 103 views
1 answer 109 views
1 answer 100 views
1 answer 126 views
...