Skip to content

How to Find the Shortest Word in C++

The challenge

Simple, given a string of words, return the length of the shortest word(s).

The string will never be empty and you do not need to account for different data types.

The solution in C++

Option 1:

int find_short(const std::string &str) { std::istringstream inp(str); std::string s; int len = -1; while (std::getline(inp, s, ' ')) if (s.length() < len) len = s.length(); return len; }
Code language: C++ (cpp)

Option 2:

int find_short(std::string str) { std::istringstream iss(str); std::vector<std::string> vec{ std::istream_iterator<std::string>(iss), {} }; return std::min_element(vec.begin(), vec.end(), [](const std::string& s1, const std::string& s2) { return s1.length() < s2.length(); })->length(); }
Code language: C++ (cpp)

Option 3:

#include <sstream> int find_short(std::string str) { std::stringstream ss(str); auto buff = std::string(); auto shorter = std::numeric_limits<size_t>::max(); while (ss >> buff) shorter = min(shorter, buff.size()); return shorter; }
Code language: C++ (cpp)

Test cases to validate our solution

Describe(Tests) { It(Sample_Test_Cases) { Assert::That(find_short("bitcoin take over the world maybe who knows perhaps"), Equals(3)); Assert::That(find_short("turns out random test cases are easier than writing out basic ones"), Equals(3)); Assert::That(find_short("lets talk about javascript the best language"), Equals(3)); Assert::That(find_short("i want to travel the world writing code one day"), Equals(1)); Assert::That(find_short("Lets all go on holiday somewhere very cold"), Equals(2)); Assert::That(find_short("Let's travel abroad shall we"), Equals(2)); } };
Code language: C++ (cpp)

See also  Equal Sides Of An Array in Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x