Sort an array of strings according to string lengths in C++

C++Server Side ProgrammingProgramming

Here we will see how to sort a list of strings based on their lengths. So if a string has less number of characters, then that will be placed first, then other longer strings will be placed. Suppose the strings are

str_list = {“Hello”, “ABC”, “Programming”, “Length”, “Population”}

after sorting, they will be −

str_list = {“ABC”, “Hello”, “Length”, “Population”, “Programming”}

Here we will create our own comparison logic to sort them. That comparison logic will be used in the sort function in C++ STL.

Algorithm

compare(str1, str2):
Begin
   if length of str1 < length of str2, then
      return 1
   return 0
End

Example

 Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
int compare(string str1, string str2){
   if(str1.length() < str2.length())
   return 1;
   return 0;
}
main(){
   string str_list[] = {"Hello", "ABC", "Programming", "Length", "Population"};
   int n = 5;
   sort(str_list, str_list + n, compare);
   for(int i = 0; i<n; i++){
      cout << str_list[i] << " ";
   }
}

Output

ABC Hello Length Population Programming
raja
Published on 25-Sep-2019 11:49:37
Advertisements