Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

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 98 views
1 answer 80 views
1 answer 78 views
1 answer 81 views
1 answer 86 views
1 answer 79 views
1 answer 100 views
...