if (strlen(colorSpec) != 4 && strspn(colorSpec, "12345678") = 4) FAIL;
So strspn, perfect for what I need!
before:
int ok = 1;
if (strlen(colorSpec) == 4) {
for (int i = 0; i < 4; i++) {
char c = colorSpec[i];
if (c < '1' || c > '8') { ok = 0; break; }
}
} else ok = 0;
after:
strspn() returns the length of the leading substring
consisting ONLY of characters in the allowed set...
if (strlen(colorSpec) != 4 && strspn(colorSpec, "12345678") = 4) FAIL;
So strspn, perfect for what I need!
before:
int ok = 1;
if (strlen(colorSpec) == 4) {
for (int i = 0; i < 4; i++) {
char c = colorSpec[i];
if (c < '1' || c > '8') { ok = 0; break; }
}
} else ok = 0;
after:
strspn() returns the length of the leading substring
consisting ONLY of characters in the allowed set...
if (strlen(colorSpec) != 4 && strspn(colorSpec, "12345678") = 4) FAIL;
Performance probably isn't critical in your use-case, but the solution
using 'strspn' was three times as slow as doing the explicit code.
(Test string was a fixed "8725" and tested 100M times.)
This is not surprising since strspn doesn't know that the substring is ordered so doesn't need to test every character of the input string
against every every character of the substring, at least while there is
a match.
So strspn, perfect for what I need!
before:
int ok = 1;
if (strlen(colorSpec) == 4) {
for (int i = 0; i < 4; i++) {
char c = colorSpec[i];
if (c < '1' || c > '8') { ok = 0; break; }
}
} else ok = 0;
after:
strspn() returns the length of the leading substring
consisting ONLY of characters in the allowed set...
if (strlen(colorSpec) != 4 && strspn(colorSpec, "12345678") = 4) FAIL;
On Fri, 21 Nov 2025 18:41:01 -0000 (UTC), Michael Sanders wrote:
So strspn, perfect for what I need!
before:
int ok = 1;
if (strlen(colorSpec) == 4) {
for (int i = 0; i < 4; i++) {
char c = colorSpec[i];
if (c < '1' || c > '8') { ok = 0; break; }
}
} else ok = 0;
after:
strspn() returns the length of the leading substring
consisting ONLY of characters in the allowed set...
if (strlen(colorSpec) != 4 && strspn(colorSpec, "12345678") = 4) FAIL;
Actually is should be:
if (strlen(colorSpec) != 4 || strspn(colorSpec, "12345678") != 4) FAIL;
Excuse the extra posts, got excited.
Sorry, I read threads in order so commented on this in my earlier reply.
int i = 0;
while (i < 4 && colorSpec[i] >= '1' && colorSpec[i] <= '8') i++;
int ok = i == 4 && colorSpec[i] == 0;
| Sysop: | Tetrazocine |
|---|---|
| Location: | Melbourne, VIC, Australia |
| Users: | 14 |
| Nodes: | 8 (0 / 8) |
| Uptime: | 237:53:46 |
| Calls: | 184 |
| Files: | 21,502 |
| Messages: | 82,415 |