Programming Utilities Guide

String Manipulation

The len() macro returns the length of the string (number of characters) in its argument. So

len(abcdef)

is 6, and

len((a,b))

is 5.

The substr() macro can be used to produce substrings of strings. So

substr(s, i, n)

returns the substring of s that starts at the ith position (origin 0) and is n characters long. If n is omitted, the rest of the string is returned. When you input the following example:

substr(`now is the time',1)

it returns the following string:

ow is the time

If i or n are out of range, various things happen.

The index(s1,s2) macro returns the index (position) in s1 where the string s2 occurs, -1 if it does not occur. As with substr(), the origin for strings is 0.

translit() performs character transliteration [character substitution] and has the general form

translit(s,f,t)

that modifies s by replacing any character in f by the corresponding character in t.

Using the following input:

translit(s, aeiou, 12345)

replaces the vowels by the corresponding digits. If t is shorter than f, characters that do not have an entry in t are deleted. As a limiting case, if t is not present at all, characters from f are deleted from s.

Therefore, the following would delete vowels from s:

translit(s, aeiou)

The macro dnl() deletes all characters that follow it, up to and including the next newline. It is useful mainly for removing empty lines that otherwise would clutter m4 output. The following input, for example, results in a newline at the end of each line that is not part of the definition:

define(N, 100) 
define(M, 200) 
define(L, 300)

So the new-line is copied into the output where it might not be wanted. When you add dnl() to each of these lines, the newlines disappear. Another method of achieving the same result is to type:

divert(-1) 
define(...) 
...  
divert