]> git.ozlabs.org Git - ccan/blob - ccan/string/string.h
strsplit()
[ccan] / ccan / string / string.h
1 #ifndef CCAN_STRING_H
2 #define CCAN_STRING_H
3 #include <string.h>
4 #include <stdbool.h>
5
6 /**
7  * streq - Are two strings equal?
8  * @a: first string
9  * @b: first string
10  *
11  * This macro is arguably more readable than "!strcmp(a, b)".
12  *
13  * Example:
14  *      if (streq(str, ""))
15  *              printf("String is empty!\n");
16  */
17 #define streq(a,b) (strcmp((a),(b)) == 0)
18
19 /**
20  * strstarts - Does this string start with this prefix?
21  * @str: string to test
22  * @prefix: prefix to look for at start of str
23  *
24  * Example:
25  *      if (strstarts(str, "foo"))
26  *              printf("String %s begins with 'foo'!\n", str);
27  */
28 #define strstarts(str,prefix) (strncmp((str),(prefix),strlen(prefix)) == 0)
29
30 /**
31  * strends - Does this string end with this postfix?
32  * @str: string to test
33  * @postfix: postfix to look for at end of str
34  *
35  * Example:
36  *      if (strends(str, "foo"))
37  *              printf("String %s end with 'foo'!\n", str);
38  */
39 static inline bool strends(const char *str, const char *postfix)
40 {
41         if (strlen(str) < strlen(postfix))
42                 return false;
43
44         return streq(str + strlen(str) - strlen(postfix), postfix);
45 }
46
47 /**
48  * strsplit - Split string into an array of substrings
49  * @ctx: the context to tallocate from (often NULL)
50  * @string: the string to split
51  * @delims: delimiters where lines should be split.
52  * @nump: optional pointer to place resulting number of lines
53  *
54  * This function splits a single string into multiple strings.  The
55  * original string is untouched: an array is allocated (using talloc)
56  * pointing to copies of each substring.  Multiple delimiters result
57  * in empty substrings.
58  *
59  * The final char * in the array will be NULL, so you can use this or
60  * @nump to find the array length.
61  *
62  * Example:
63  *      unsigned int count_long_lines(const char *text)
64  *      {
65  *              char **lines;
66  *              unsigned int i, long_lines = 0;
67  *
68  *              // Can only fail on out-of-memory.
69  *              lines = strsplit(NULL, string, "\n", NULL);
70  *              for (i = 0; lines[i] != NULL; i++)
71  *                      if (strlen(lines[i]) > 80)
72  *                              long_lines++;
73  *              talloc_free(lines);
74  *              return long_lines;
75  *      }
76  */
77 char **strsplit(const void *ctx, const char *string, const char *delims,
78                  unsigned int *nump);
79 #endif /* CCAN_STRING_H */