Find the position of a character in a string

Last-Updated: 2021-08-30

Sources

Macros corresponding to Cs strchr and strrchr

In C, the functions strchr() and strrchr() return respectively the first or the last occurrence of a character in a string. The following is a recreation of these functions (strchr.txt) in groff by Denis M. Wilson.

\# .----------------------------.
\# |				|
\# |  strchr reg string char	|
\# |  ------ --- ------ ----	|
\# |				|
\# |  strrchr reg string char	|
\# |  ------- --- ------ ----	|
\# |				|
\# `----------------------------'
.
\# Position of characters in strings
.
\# .strchr reg string char
\# defines the number register to be the first position in
\# string of the character CW char, or \-1 if the character
\# does not occur in the string.
\#Strings are indexed from 0.
.
\# .strrchr reg string char
\# defines the number register to be the last position in
\# string of the character char, or \-1 if the character
\# does not occur in the string.
.
.eo
.de strchr
.nr \$[1] 0-1
.length str-len \$[2]
.nr str-i 0-1 1
.while \n+[str-i]<\n[str-len] \{\
.	ds str-tmp \$[2]
.	substring str-tmp \n[str-i] \n[str-i]
.	if \[str]\*[str-tmp]\[str]\$[3]\[str] \{\
.		nr \$[1] \n[str-i]
.		break
.	\}
.\}
..
.
.de strrchr
.nr \$[1] 0-1
.length str-len \$[2]
.nr str-i \n[str-len] -1
.while \n+[str-i]>=0 \{\
.	ds str-tmp \$[2]
.	substring str-tmp \n[str-i] \n[str-i]
.	if \[str]\*[str-tmp]\[str]\$[3]\[str] \{\
.		nr \$[1] \n[str-i]
.		break
.	\}
.\}
..
.ec