0

I am parsing a text-file. While parsing, I want to skip certain characters (space, line-break, comma, period). In PHP, one may check the existence of a variable in an array with in_array(char, array), but things are obviously different given we are working with pointers.

I am currently writing it like this (excuse the weird formatting)

if (c == ' '  || 
    c == '\n' || 
    c == '.'  || 
    c == ',') {

  continue;
}

But it feels a bit dumb. Is there a smarter/more compact way to perform multiple comparisons like this?

krystah
  • 3,346
  • 2
  • 24
  • 41
  • 1
    Hard to guess what's "dumb" about it. Maybe you ought to write a one-liner isPunctuation(char) function. Maybe you shouldn't [try too hard](http://stackoverflow.com/questions/26124620/why-does-msvc-emit-a-useless-movsx-before-performing-this-bit-test). – Hans Passant Oct 27 '14 at 17:53

3 Answers3

3

Try this:

switch(c) {
  case ' ':
  case '\n':
  case '.:
  case ',':
    continue;
}
Linuxios
  • 33,279
  • 13
  • 86
  • 114
3

Another choice would be to use strchr to check if a given character is in a given string:

if (strchr(" \n.,", c)
    continue;
Brian Campbell
  • 306,970
  • 56
  • 356
  • 335
1

Use a function and pass a string with your characters:

_Bool Check( char a , char* str )
{
    while( *str )
    { 
        if( *str == a )
        {
            return true ;
        }

        str++ ;
    }

return false ;
}

Check( c , ",.\n " ) ;
2501
  • 24,953
  • 4
  • 46
  • 86