In this C++ tutorial, you shall learn how to find the smallest string in an array based on length, with example programs.
Find string with least length in an Array in C++
To find the smallest string in array based on length in C++
- Initialize
smallest
with first element of array. - For each element in the array:
- Compare the length of
smallest
with that of this element. - If length of
smallest
is greater than that of this element, then updatesmallest
with the element.
- Compare the length of
smallest
contains the string of smallest length from given string array.
We will use C++ Greater than Operator for comparison.
ADVERTISEMENT
C++ Program
In the following program, we take a string array strArr initialized with some elements, and find the string with the smallest length among the elements of this array.
main.cpp
#include <iostream> using namespace std; int main() { //a string array string x[] = {"apple", "fig", "banana", "mango"}; //get length of string array int len = sizeof(x) / sizeof(x[0]); //get array length // find smallest only if there is atleast one element in array if ( len > 0 ) { //start with first element as smallest string smallest = x[0]; for ( int i = 1; i < len; i++ ) { if ( smallest.length() > x[i].length() ) { smallest = x[i]; //update smallest } } cout << "Smallest : " << smallest << endl; } else { cout << "No elements in the array." << endl; } }
Output
Smallest : fig
Conclusion
In this C++ Tutorial, we learned how to find the string with smallest length of elements in a given string array, with the help of example C++ programs.