I know how to do this in every other language that I know, but I'm just starting Lisp and not quite getting it. My idea of
Seems heavy-handed. Is there some better way to do this? I'm trying to write a function that, given a string, returns a string with the letters sorted. So, for example:
gate => aegt
house => ehosu
door => door
This routine will be used as part of an anagram-finder.
Thanks!
The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string. Now use Arrays. sort(char c[]) method to sort character array. Use the String class constructor to create a sorted string from a char array.
We can use LINQ to sort characters of a string in alphabetical order in C#. The idea is to use LINQ's OrderBy() method to create a sorted collection of all characters in the string, and then combine all characters together with the String. Concat() method.
You can use the sort function from the Standard template library of C++ by including the <algorithm> header file in your code. Syntax: sort(first iterator, last iterator), where the first and last iterators are the starting and ending index of the string respectively.
In Common Lisp strings are sequences, and sort
works on any sequence type, so it will do the trick.
Here's an example:
(let ((the-string (copy-seq "this is the string")))
(sort the-string #'char-lessp))
;; => " eghhiiinrsssttt"
And here's the Hyperspec entry for sort
and stable-sort
. Just pick your predicate (the second argument to sort
) to get your desired sort order.
Note that I used copy-seq
in the example because sort
is destructive - it modified the string in-place.
The sort
function takes a sequence, which a string already is, so your only problem is finding the right comparison function. Characters are not numbers, so you should use the character comparison functions, e.g. char>
:
* (sort (copy-seq "hello") #'char>)
"ollhe"
A string is a sequence of characters. sort sorts sequences so it sorts a string like it sorts a list:
(setq tester (copy-seq "lkjashd")) => "lkjashd"
(stable-sort tester #'char-lessp) => "adhjkls"
tester => "adhjkls" ; NB: it mutates the string!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With