9

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?

  • 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. – Sato Katsura Oct 1 '15 at 14:17
  • Your current solution is already both elegant and idiomatic. – romainl Oct 1 '15 at 14:27
  • @Soto Yes, that's what I understand by elegant. – René Nyffenegger Oct 1 '15 at 14:27
  • Skip the '.' in the split part. – Christian Brabandt Oct 1 '15 at 14:39
  • 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. – Sato Katsura Oct 1 '15 at 15:08
6

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

!!rev
1

From wikia

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

For more see: :h revins

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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