13

I am trying to reverse a string, so that 'abc defg hij' becomes 'jih gfed cba'. The solution I came up with is

join(reverse(split(l:text, '.\zs')), '')

Is there a more elegant solution or should I stick with what I have come up with?

10
  • 1
    It depends on what you mean by "elegant". There is no internal function dedicated to reversing a string, if that's what you're asking. If you mean doing it with two or less calls to internal functions and no additional statements, that doesn't seem to be possible, either. Oct 1, 2015 at 14:17
  • 1
    Your current solution is already both elegant and idiomatic.
    – romainl
    Oct 1, 2015 at 14:27
  • 1
    Skip the '.' in the split part. Oct 1, 2015 at 14:39
  • 1
    @SatoKatsura actually, I think it is more efficient, because the regexp engine does not need to match anything. Furthermore, this is the prefered way from the documentation. Oct 1, 2015 at 14:55
  • 1
    @ChristianBrabandt According to the manual, split() without the {keepempty} option should remove a single empty item at the beginning, and a single empty item at the end. It currently removes all empty items, including the ones in the middle of the list (which is more useful than the documented behaviour if you ask me, but you probably aren't). I think this has been discussed recently on vim_dev. Oct 1, 2015 at 15:08

3 Answers 3

11

Your solution is very elegant! An alternative if you are in Unix based env:

!!rev
6

From wikia

vnoremap <Leader>r c<C-O>:set revins<CR><C-R>"<Esc>:set norevins<CR>

For more see: :h revins

5

If you are using a unix-like system, in vim, type ex-command :%! rev

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.