Less well-known, but extremely useful (and standard, since C89 is the value "forever") function in the C library, provide information in a single call. In fact, there are several functions: - embarrassment of wealth. The following are important for this:
7.21.5.3 strcspn function
Summary
#include <string.h> size_t strcspn(const char *s1, const char *s2);
Description
The strcspn function calculates the length of the maximum initial segment of the string pointed to by s1, which consists entirely of characters not from the string pointed to by s2.
Returns
The strcspn function returns the length of the segment.
7.21.5.4 strpbrk function
Summary
#include <string.h> char *strpbrk(const char *s1, const char *s2);
Description
The strpbrk function finds the first occurrence in the string pointed to by s1 of any character from the string pointed to by s2.
Returns
The strpbrk function returns a character pointer or a null pointer if there is no character from s2 found in s1.
The question asks "for each char in the string ... if it is in the list of invalid characters".
Using these functions, you can write:
size_t len = strlen(test); size_t spn = strcspn(test, "invald"); if (spn != len) { ...there a problem... }
Or:
if (strpbrk(test, "invald") != 0) { ...there a problem... }
Which is better depends on what else you want to do. There is also a related function, strspn() , which is sometimes useful (whitelist instead of blacklist).
Jonathan Leffler Jul 01 '09 at 23:07 2009-07-01 23:07
source share