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,587
  • 2
  • 25
  • 43
  • 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
  • 34,849
  • 13
  • 91
  • 116
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
  • 322,767
  • 57
  • 360
  • 340
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
  • 25,460
  • 4
  • 47
  • 87