Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common-Lisp: How to sort the characters of a string?

Tags:

common-lisp

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

  • make a list of characters
  • convert to ascii values
  • sort
  • convert back to characters
  • convert back to a string

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!

like image 799
Olie Avatar asked Aug 17 '13 15:08

Olie


People also ask

How do I sort characters in a string?

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.

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

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.

How do you sort string C++?

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.


3 Answers

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.

like image 67
jbm Avatar answered Nov 18 '22 20:11

jbm


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"
like image 28
svk Avatar answered Nov 18 '22 18:11

svk


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!
like image 23
Sylwester Avatar answered Nov 18 '22 19:11

Sylwester