May 24, 2021 Vim
Vim has many built-in functions to manipulate strings. In this chapter we'll cover some of the most important string functions.
The first function described is
strlen
Execute the following command:
:echom strlen("foo")
Vim
3
which is
"foo"
Now try the following command:
:echom len("foo")
Vim shows
3
F
or strings,
len
and
strlen
the same effect.
We'll look back later in this book to
len
Execute the following command (note that the
echo
echom
:echo split("one two three")
Vim shows
['one','two','three']
split
function cuts the string into a list.
We'll give you a brief list, but don't get tangled up in it right now.
You can also specify a separator instead of Blank.
:echo split("one,two,three", ",")
Vim once again displays
['one','two','three']
split
second parameter is ',' which means ',' cutting.
Not only can you cut strings, you can also connect them. Follow these commands:
:echo join(["foo", "bar"], "...")
Vim will
foo...bar
。
Don't care about list syntax for the time being.
split
and
join
can work together.
Execute the following command:
:echo join(split("foo bar"), ";")
Vim shows
foo;bar
。
First we cut
"foo bar"
lists, and then we connect the lists into strings with a sign as a separator.
Vim has two functions to convert string case. Execute the following command:
:echom tolower("Foo")
:echom toupper("Foo")
Vim
foo
and
FOO
It's easy to understand.
In many languages, such as Python, there is a convention to force strings into small case to implement case-independent comparisons before comparing them. T his is not required in Vimscript because there are case-insensitive comparison operators. I f you can't remember, read the chapter on comparison again. If you can't remember, it's Chapter 22.
You are free to
tolower
==#
. . and
==?
t
o achieve case-sensitive comparisons. T
he Vimscript community has no obvious preference for this.
Select one and be consistent in all your scripts.
Execute:
:echo split('1 2')
:echo split('1,,,2',',')
Do they behave consistently?
Read
:help splt()
Read
:help join()
Read
:help functions
browse the built-in functions about String. U
se
/
command to assist you (remember that Vim's help files can be viewed as normal files). T
here are a lot of functions here, so don't get tangled up in the documentation for each function.
It's enough to make an impression on yourself so that you can use it from time to time in the future.