home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c      Meh, in C you gotta define EVERYTHING      243,242 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 242,032 of 243,242   
   Ben Bacarisse to Michael Sanders   
   Re: strspn()   
   22 Nov 25 02:41:11   
   
   From: ben@bsb.me.uk   
      
   Michael Sanders  writes:   
      
   > 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;   
      
   There's no need for the strlen test:   
      
     int i = 0;   
     while (i < 4 && colorSpec[i] >= '1' && colorSpec[i] <= '8') i++;   
     int ok = i == 4 && colorSpec[i] == 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;   
      
   Hmm... don't you mean   
      
     if (strlen(colorSpec) != 4 || strspn(colorSpec, "12345678") != 4) FAIL;   
      
   You could also write the positive test explicitly like this, again   
   without strlen:   
      
     static bool in_range(char c) { return c >= '1' && c <= '8'; }   
   ...   
     in_range(colorSpec[0]) && in_range(colorSpec[1]) &&   
     in_range(colorSpec[2]) && in_range(colorSpec[3]) &&   
     colorSpec[4] == 0   
      
   --   
   Ben.   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca