Replacing a vertical list of characters with a sequence of numbers in VIM

During my spare time, I try to learn C. Often I find myself having to create arrays, and fill these with data manually. Since I hate, and let me emphasize, hate, doing repetitive tasks, I wanted to show you guys how to create an array with 6 elements as simple as possible.

Consider the following; you want to create an array of strings with 6 elements, where each element can hold a maximum of 25 characters. Hence, you type the following:

#include <stdio.h>

int main(int argc, char argv[])
char my_array[6][26];

strcpy(my_array[0], "Something");
strcpy(my_array[1], "Something else");
strcpy(my_array[2], "Something different");
// etcetera

return 1;

Now, that wasn’t very tiresome, but what if you had to enter 10 elements, or even 50? Typing strcpy(my_array[x], “blahblah”); that many times can even make the most patient person go nuts. If you’re a VIM user, this process can however be simplified quite a bit.

First, start VIM. Next, type ‘strcpy(my_array[x], “”‘);’, and yank this line by pressing ‘yy’. Now, to repeat this process 5 times, simply type “5p”. You should now have 6 lines containing:

strcpy(my_array[x], "");
strcpy(my_array[x], "");
strcpy(my_array[x], "");
strcpy(my_array[x], "");
strcpy(my_array[x], "");
strcpy(my_array[x], "");

The final step is now to replace all the x characters with a sequence of numbers, ranging from 0 to 5. By using the Nexus plugin, located here, you can do this with one neat command.

With the plugin installed, replace the first occurance of ‘x’ with 0. Then, enter Visual Block Mode (C v), and select the remaining x characters. Now, enter the command: :’< ,'>s/\%V./\, and all the x characteres is replaced with a sequence of numbers, ranging from 1 to 5. You should now have:

strcpy(my_array[0], "");
strcpy(my_array[1], "");
strcpy(my_array[2], "");
strcpy(my_array[3], "");
strcpy(my_array[4], "");
strcpy(my_array[5], "");

Neat, huh? If you want to perform the task again, you will see that s1 continues from where it stopped in the above example. To reset the s1 variable, run ‘:call s1.reset()’.

Shares 0