jacob navia said:
Can you give a better solution?
When the character set is large, such as the character set
of Unicode, one might not want to fill a lookup table. When
the set of characters to be found is small, the following
approach might help to eliminate some comparisons:
The program below stores the bits that are set in /every/
character of the set into »t« and then skips all characters
of the string where those bits are not all set.
#include <stdio.h>
#include <string.h>
/*prints all positions where a character from the array c appears
in the array s, where z is the size of s, and n is the size of c. */
void f
( size_t const z, char const * const s, size_t const n, char const * const c )
{ unsigned char t = -1; for( size_t i = 0; i < n; ++i )t &=c[ i ];
unsigned char b = 0; for( size_t i = 0; i < n; ++i )b |=c[ i ];
for( size_t i = 0; i < z; ++i )
{ char const r = i[ s ];
if((( r & t )== t )&&(( r & !b )== 0 )) /* the bits-check optimization */
{ for( size_t j = 0; j < n; ++j )if( r == j[ c ] )
{ printf( "found %c at %d.\n", r, i ); goto over; }
printf( "Did an exhaustive search loop, but no match was found.\n" );
over: ; }
else printf( "Skipped an exhaustive search loop.\n" ); }}
int main( void )
{ char const * const s = "This sentence"; char const * const c = "aeiou";
f( strlen( s ), s, strlen( c ), c ); }
Skipped an exhaustive search loop.
Skipped an exhaustive search loop.
found i at 2.
Did an exhaustive search loop, but no match was found.
Skipped an exhaustive search loop.
Did an exhaustive search loop, but no match was found.
found e at 6.
Skipped an exhaustive search loop.
Skipped an exhaustive search loop.
found e at 9.
Skipped an exhaustive search loop.
Did an exhaustive search loop, but no match was found.
found e at 12.