]> git.ipfire.org Git - thirdparty/man-pages.git/commitdiff
strsep.3: port strtok(3) example
authorнаб <nabijaczleweli@nabijaczleweli.xyz>
Mon, 24 Jan 2022 22:43:17 +0000 (23:43 +0100)
committerAlejandro Colomar <alx.manpages@gmail.com>
Tue, 25 Jan 2022 15:59:10 +0000 (16:59 +0100)
Each time I use strsep I want something like this;
this serves to snappily highlight the programming model,
esp. in contrast to strtok_r ‒ I elided the long
(and, frankly, gratuitous, even there) argv explanation
‒ if you need it, you can read the original
(or the usage string, or the seven-line main)

Signed-off-by: Ahelenia Ziemiańska <nabijaczleweli@nabijaczleweli.xyz>
Signed-off-by: Alejandro Colomar <alx.manpages@gmail.com>
man3/strsep.3

index fb5f7fd1a2420b67797eef55cdc59d9bcf9ebe90..3ce4fc35def4a0e7a93183973b6a44b5f546fcd7 100644 (file)
@@ -118,6 +118,56 @@ This function modifies its first argument.
 This function cannot be used on constant strings.
 .IP *
 The identity of the delimiting character is lost.
+.SH EXAMPLES
+The program below is a port of the one found in
+.BR strtok (3),
+which, however, doesn't discard multiple delimiters or empty tokens:
+.PP
+.in +4n
+.EX
+.RB "$" " ./a.out \(aqa/bbb///cc;xxx:yyy:\(aq \(aq:;\(aq \(aq/\(aq"
+1: a/bbb///cc
+         \-\-> a
+         \-\-> bbb
+         \-\->
+         \-\->
+         \-\-> cc
+2: xxx
+         \-\-> xxx
+3: yyy
+         \-\-> yyy
+4:
+         \-\->
+.EE
+.in
+.SS Program source
+\&
+.EX
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+int
+main(int argc, char *argv[])
+{
+    char *token, *subtoken;
+
+    if (argc != 4) {
+        fprintf(stderr, "Usage: %s string delim subdelim\en",
+                argv[0]);
+        exit(EXIT_FAILURE);
+    }
+
+    for (int j = 1; (token = strsep(&argv[1], argv[2])); j++) {
+        printf("%d: %s\en", j, token);
+
+        while ((subtoken = strsep(&token, argv[3])))
+            printf("\et \-\-> %s\en", subtoken);
+    }
+
+    exit(EXIT_SUCCESS);
+}
+.EE
 .SH SEE ALSO
 .BR index (3),
 .BR memchr (3),