Sort file names in lexicographical order of their extensions
Last Updated :
09 Mar, 2023
Given an array of strings Files[], representing name of some files, the task is to sort the array based on the lexicographical order of the extensions of the file names. If more than one files have the same extension, then sort them in lexicographically.
Examples:
Input: files[] = {"ajay.cpp", "pchy.pdf", "loki.docx", "raju.zip" }
Output: ajay.cpp, loki.docx, pchy.pdf, raju.zip
Explanation:
Lexicographically sorted order of "cpp" < "docx" < "pdf" < "zip"
Input: files[] = {"abc.cpp", "bcd.cpp", "ab.cpp", "efg.zip"}
Output: ab.cpp, abc.cpp, bcd.cpp, efg.zip
Explanation:
Since the file names { "abc.cpp", "bcd.cpp", "ab.cpp" } have same extension, they are sorted lexicographical order of their names.
Approach: Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
// C++ Program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Comparator function to sort an array of strings
// based on the extension of their file names
bool custom(string s1, string s2)
{
// Stores index of '.' in s1
size_t i = s1.find('.');
// Stores index of '.' in s2
size_t j = s2.find('.');
// Stores name of extension of s2
string d = s1.substr(i + 1);
// Stores name of extension of s2
string e = s2.substr(j + 1);
// If both files have the
// same extension name
if (d == e) {
// Return lexicographically
// smaller of the two strings
return s1 < s2;
}
return d < e;
}
// Function to sort the files names
// based on the name of their extension
void sortfromextension(vector<string>& files)
{
// Sort file names in lexicographical
// order of their extensions
sort(files.begin(), files.end(), custom);
// Print files in sorted form
// based on extension names
for (auto s : files) {
cout << s << ", ";
}
}
// Driver Code
int main()
{
vector<string> files
= { "ajay.cpp", "pchy.pdf",
"loki.docx", "raju.zip" };
sortfromextension(files);
return 0;
}
Java
// Java program for above approach
import java.util.*;
import java.lang.*;
class GFG
{
// Function to sort the files names
// based on the name of their extension
static void sortfromextension(String[] files)
{
// Sort file names in lexicographical
// order of their extensions
Arrays.sort(files, new Comparator<String>(){
public int compare(String s1,String s2){
// Stores index of '.' in s1
int i = s1.indexOf('.');
// Stores index of '.' in s2
int j = s2.indexOf('.');
// Stores name of extension of s2
String d = s1.substring(i + 1);
// Stores name of extension of s2
String e = s2.substring(j + 1);
return (d.equals(e))?(s1.compareTo(s2)<0?-1:1):(d.compareTo(e)<0?-1:1);
}
});
// Print files in sorted form
// based on extension names
for (int i = 0; i < files.length - 1; i++)
{
System.out.print(files[i] + ", ");
}
System.out.print(files[files.length - 1]);
}
// Driver function
public static void main (String[] args)
{
String[] files
= { "ajay.cpp", "pchy.pdf",
"loki.docx", "raju.zip" };
sortfromextension(files);
}
}
// This code is contributed by offbeat
C#
using System;
using System.Linq;
class Program
{
// Function to sort the files names
// based on the name of their extension
static void SortFromExtension(string[] files)
{
// Sort file names in lexicographical
// order of their extensions
Array.Sort(files, (s1, s2) =>
{
// Stores index of '.' in s1
int i = s1.IndexOf('.');
// Stores index of '.' in s2
int j = s2.IndexOf('.');
// Stores name of extension of s2
string d = s1.Substring(i + 1);
// Stores name of extension of s2
string e = s2.Substring(j + 1);
return (d == e) ? string.Compare(s1, s2, StringComparison.Ordinal) : string.Compare(d, e, StringComparison.Ordinal);
});
// Print files in sorted form
// based on extension names
Console.WriteLine(string.Join(", ", files));
}
static void Main(string[] args)
{
string[] files =
{
"ajay.cpp", "pchy.pdf",
"loki.docx", "raju.zip"
};
SortFromExtension(files);
}
}
Python3
# Python
import re
def SortFromExtension(files):
# Sort file names in lexicographical
# order of their extensions
files.sort(key=lambda s: re.split("\.([^.]+)", s)[1])
# Print files in sorted form
# based on extension names
print(", ".join(files))
if __name__ == "__main__":
files = ["ajay.cpp", "pchy.pdf", "loki.docx", "raju.zip"]
SortFromExtension(files)
#contributed by akashish__
JavaScript
// Javascript program for the above approach
function SortFromExtension(files) {
// Sort file names in lexicographical
// order of their extensions
files.sort(function(a, b) {
let ext1 = a.split('.').pop();
let ext2 = b.split('.').pop();
if (ext1 < ext2) {
return -1;
} else if (ext1 > ext2) {
return 1;
} else {
return a.localeCompare(b);
}
});
// Print files in sorted form
// based on extension names
console.log(files.join(', '));
}
let files = ["ajay.cpp", "pchy.pdf", "loki.docx", "raju.zip"];
SortFromExtension(files);
// This code is contributed by rishabmalhdjio
Outputajay.cpp, loki.docx, pchy.pdf, raju.zip,
Time Complexity: O(N * log(N))
Auxiliary Space: O(1)
Similar Reads
Sort an Array of Strings in Lexicographical order Given an array of strings arr[] of size n, the task is to sort all the strings in lexicographical order. Examples:Input: arr[] = ["banana", "apple", "cherry"]Output: ["apple", "banana", "cherry"]Explanation: All strings are sorted alphabetically. "apple" comes before "banana", and "banana" before "c
11 min read
Sort a list of strings in lexicographical order in Python We are given a list of strings and our task is to sort them in lexicographical order, which means alphabetical order either from A to Z (ascending) or Z to A (descending). This is a common operation when organizing or comparing strings in Python. For example:Input: ["banana", "apple", "cherry", "dat
2 min read
Power Set in Lexicographic order This article is about generating Power set in lexicographical order. Examples : Input : abcOutput : a ab abc ac b bc cThe idea is to sort array first. After sorting, one by one fix characters and recursively generates all subsets starting from them. After every recursive call, we remove last charact
9 min read
Lexicographically largest string for given dictionary order Given an array arr[] of N strings and a string order which represents the new alphabetical order of the string. The task is to find the lexicographically largest string based on the given order. Examples: Input: arr[] = {"abc", "abd", "abz"}, order = "abczdefghijklmnopqrstuvwxy" Output: abd Explanat
14 min read
Sort an array of strings lexicographically based on prefix Given an array of strings arr[] of size N, the task is to sort the array of strings in lexicographical order and if while sorting for any two string A and string B, if string A is prefix of string B then string B should come in the sorted order. Examples: Input: arr[] = {"sun", "moon", "mock"}Â Outpu
7 min read