Sort the String Values Based on Length

The program must accept N string values as the input. The program must sort the string values based on the length of each string value in increasing order. Then the program must print the sorted string values as the output.

Note: Each of the string values has a different length.

Boundary Condition(s):
1 <= N <= 100
1 <= Length of each string value <= 100

Input Format:
The first line contains the integer N.
The next N lines contain the string value in each line.

Output Format:
The first N lines contain the sorted string values.

Example Input/Output 1:
Input:
4
lemon
embezzling
banana
ant

Output:
ant
lemon
banana
embezzling

Explanation:
The length of the string lemon is 5.
The length of the string embezzling is 10.
The length of the string banana is 6.
The length of the string ant is 3.
After sorting the string values based on their length are antlemonbananaembezzling.
Hence the output is 
ant
lemon
banana
embezzling

Example Input/Output 2:
Input:
5
orange
hello
gentleman
app
hi

Output:
hi
app
hello
orange
gentleman

#include <stdio.h>
#include <string.h>

int main() {
    int n;
    scanf("%d", &n);
    char str[n][100];

    for(int i = 0; i < n; i++) {
        scanf("%s", str[i]);
    }

    for(int i = 0; i < n; i++) {
        for(int j = i + 1; j < n; j++) {
            if(strlen(str[i]) > strlen(str[j])) {
                char temp[100];
                strcpy(temp, str[i]);
                strcpy(str[i], str[j]);
                strcpy(str[j], temp);
            }
        }
    }

    for(int i = 0; i < n; i++) {
        printf("%sn", str[i]);
    }

    return 0;
}

n = int(input())
strings = [input().strip() for _ in range(n)]

strings.sort(key=len)

for s in strings:
    print(s)
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class SortByLength {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        String[] strings = new String[n];

        for(int i = 0; i < n; i++) {
            strings[i] = scanner.next();
        }

        Arrays.sort(strings, Comparator.comparingInt(String::length));

        for(String s : strings) {
            System.out.println(s);
        }
    }
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool compare(const string &a, const string &b) {
    return a.length() < b.length();
}

int main() {
    int n;
    cin >> n;
    vector<string> strings(n);

    for(int i = 0; i < n; i++) {
        cin >> strings[i];
    }

    sort(strings.begin(), strings.end(), compare);

    for(const string &s : strings) {
        cout << s << endl;
    }

    return 0;
}
Previous Article

Function printXMultiples - CTS PATTERN

Next Article

Twisted Prime

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *