Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort characters in a string?

Tags:

I would like to sort the characters in a string.

E.g.

echo cba | sort-command abc 

Is there a command that will allow me to do this or will I have to write an awk script to iterate over the string and sort it?

like image 328
dogbane Avatar asked Mar 03 '10 18:03

dogbane


People also ask

How do you sort a string character in Python?

Sort a Python String with Sorted Python comes with a function, sorted() , built-in. This function takes an iterable item and sorts the elements by a given key. The default value for this key is None , which compares the elements directly. The function returns a list of all the sorted elements.

Can we use sort function on string?

The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.

How do you sort a character in a string in C#?

Firstly, set a string array. string[] values = { "tim", "amit", "tom", "jack", "saurav"}; Use the Sort() method to sort.

How do you sort a char array?

sort(char[] a, int fromIndex, int toIndex) method sorts the specified range of the specified array of chars into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.


2 Answers

echo cba | grep -o . | sort |tr -d "\n" 
like image 87
ghostdog74 Avatar answered Sep 23 '22 15:09

ghostdog74


Please find the following useful methods:

Shell

Sort string based on its characters:

echo cba | grep -o . | sort | tr -d "\n" 

String separated by spaces:

echo 'dd aa cc bb' | tr " " "\n" | sort | tr "\n" " " 

Perl

print (join "", sort split //,$_) 

Ruby

ruby -e 'puts "dd aa cc bb".split(/\s+/).sort'  

Bash

With bash you have to enumerate each character from a string, in general something like:

str="dd aa cc bb"; for (( i = 0; i < ${#str[@]}; i++ )); do echo "${str[$i]}"; done 

For sorting array, please check: How to sort an array in bash?

like image 34
kenorb Avatar answered Sep 23 '22 15:09

kenorb