/g/ - Technology

install openbsd

[Make a Post]
[X]





C question Nanonymous No.1407 [D][S][L][A][C]

Is this the best way of making sure that all characters in a string are members of a specified character set? Or is there an even simpler method?

#include <string.h>

int valid(const char *str, const char *set)
{
return (strspn(str, set) == strlen(str));
}

Nanonymous No.1409 [D] >>1410

I'd use strpbrk with the complement of your set, saves you the strlen call.

Nanonymous No.1410 [D] >>1426 >>1439

>>1409
The complement of a typical set in my use case? That would have over 200 characters in it. I think the added overhead from looping through 200 chars (or however strpbrk() does it) would kill any performance gains.
Is writing a dedicated function here a good idea? Presumably the optimized libc functions would still be faster, even if not used optimally.

Nanonymous No.1426 [D]

>>1410
If the performance of your program REALLY depends on this function, you can try with a lookup table.

Nanonymous No.1429 [D] >>1440

return !str[strspn(str, set)];

Nanonymous No.1439 [D] >>1440

>>1410
>That would have over 200 characters in it. I think the added overhead from looping through 200 chars (or however strpbrk() does it) would kill any performance gains.
m8, your set is probably compiled into a 256 cells lookup table, it doesn't change anything what size your set is.

Nanonymous No.1440 [D] >>1444

>>1429
hey that's actually a pretty neat solution, thanks
>>1439
nowhere in the documentation does it mention that there is a 256 char limit

Nanonymous No.1444 [D] >>1445

>>1440
>nowhere in the documentation does it mention that there is a 256 char limit
Think for 3 seconds before posting

Nanonymous No.1445 [D] >>1459

>>1444
>b-b-but muh unicode muh wchar
ok i get it

Nanonymous No.1459 [D]

>>1445
>char *strpbrk(const char *s, const char *accept);
>wchar