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++

  1. Initialize smallest with first element of array.
  2. For each element in the array:
    1. Compare the length of smallest with that of this element.
    2. If length of smallest is greater than that of this element, then update smallest with the element.
  3. smallest contains the string of smallest length from given string array.

We will use C++ Greater than Operator for comparison.

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
ADVERTISEMENT

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.