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 length of the second smallest word in a string with C++

2 Answers

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

int secondSmallestWordLength(const std::string& str) {
    std::vector<std::string> vec;
    std::string word;
    
    for (char ch : str) {
        if (ch == ' ') {
            vec.push_back(word);
            word = "";
        } else {
            word += ch;
        }
    }
    
    vec.push_back(word);
    
    if (vec.size() < 2) {
        return false;
    }
    
    std::vector<int> lengths;
    for (const std::string& word : vec) {
        lengths.push_back(word.length());
    }
    
    std::sort(lengths.begin(), lengths.end());
    
    return lengths[1];
}

int main() {
    std::string str = "java c++ python c# javascript";
    
    std::cout << secondSmallestWordLength(str) << std::endl;
}




/*
run:

3

*/

 



answered Mar 27, 2024 by avibootz
edited Mar 27, 2024 by avibootz
0 votes
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

int secondSmallestWordLength(const std::string& str) {
    std::istringstream iss(str);
     
    std::vector<std::string> vec;
     
    copy(std::istream_iterator<std::string>(iss),
        std::istream_iterator<std::string>(),
        back_inserter(vec));
    
    if (vec.size() < 2) {
        return false;
    }
    
    std::vector<int> lengths;
    for (const std::string& word : vec) {
        lengths.push_back(word.length());
    }
    
    std::sort(lengths.begin(), lengths.end());
    
    return lengths[1];
}

int main() {
    std::string str = "java c++ python c# javascript";
    
    std::cout << secondSmallestWordLength(str) << std::endl;
}



/*
run:

3

*/

 



answered Mar 27, 2024 by avibootz

Related questions

...