Here is one possible way to implement this using a temporary buffer:
(defun sort-string (string &optional reverse)
"sorts an input string, using a temporary buffer"
;;(interactive "sto be sorted multiline string: ")
(with-temp-buffer
(insert string)
(let ((beg (point-min))
(end (point-max)))
(sort-lines reverse beg end)
(buffer-string)) ))
First a temprary buffer is created, then the given string is inserted, then the whole buffer is sorted, then the whole buffer is returned as a new string.
The additional parameter reverse can change the sort order.
To make this function a command, which you can call via M-x
, uncomment the (interactive)
line, but then you have to grab the output of the function in a useful way.
Evaluating following code pieces in the given order, results in the following output:
(setq my-string "zzzz\ndddd\nhhhhh\naaaaa")
"zzzz
dddd
hhhhh
aaaaa"
(setq my-string (sort-string my-string))
"aaaaa
dddd
hhhhh
zzzz"
my-string
"aaaaa
dddd
hhhhh
zzzz"
(setq my-string (sort-string my-string 'reverse))
"zzzz
hhhhh
dddd
aaaaa"
my-string
"zzzz
hhhhh
dddd
aaaaa"
sort-lines
(if applicable) - yes. But see the Elisp manual, node Sorting for other sort functions etc.