Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get length of string using Vimscript

Tags:

string

vim

This may be a very basic question, but I can't seem to find an answer with a simple Google search.

I simply want to find the length of a string using Vimscript, similar to len() function in Python. Is there a simple way to do this in Vimscript, or will I just have to loop over the string?

like image 301
Ryan Fredez Avatar asked Jun 13 '26 06:06

Ryan Fredez


2 Answers

There is len and strlen. For strings they are same.

:echo len("Hello")
:echo strlen("Hello")
like image 188
Ashwani Avatar answered Jun 16 '26 07:06

Ashwani


Note that the answer by Ashwani only works for single-byte characters, not for multi-byte characters.

There is function strlen() or len() in Vim, but they only calculates byte length of a string, instead of character length, like what len() function in Python does. We can instead use the strchars() function to get string length. I consider this one of the many hidden quirks of Vim. We just need to get accustomed to it.

like image 28
jdhao Avatar answered Jun 16 '26 06:06

jdhao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!