Search code examples
stringsortingj

Sorting words in a string by their length in J


I have the following string: s=:'when can we dance' I can find the length of each word with this: # each ;:s I can sort the lengths in ascending/descending order:(/:~) # each ;:s which gives me boxed output. But how do I get the words printed?


Solution

  • Julian does a great job of explaining the way to deal with apostrophes in his answer above, but if you disregard their presence, I would use &. (Under) with ;: (Words) to sort them according to length after they are boxed and then unboxing them.

       s=:'when can we dance' 
       (/:  # each)  &. ;: s
    we can when dance
    

    (/: # each) is the hook that orders them according to each length and &.;: boxes them and then at the end unboxes them to provide the result.