Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could i count some punctuation marks which the function ispunct doesn't have

Tags:

c++

      for (int i = 0; i < strlen(s); i++)
       if(ispunct(s[i]))

I need to write function in which i have to count punctuation marks, as follow; but ispunct function doesn't have them all . , - ; : ' " ( ) ... ? !

I tried to use the strchr, but I couldn't find the " ' " These from above are "only" considered, how I could actually count them ??

Thanks!

like image 841
JohnK Avatar asked Nov 25 '25 13:11

JohnK


2 Answers

I would just list all the characters you care about, and use find_first_of to identify if the character is there. Something like this:

bool isPunctuation(char c)
{
   static const std::string punctuations(".,-;:'\"()?");
   if (punctuations.find_first_of(c) != std::string::npos)
   {
      return true;
   }
   return false;
}
like image 149
Mats Petersson Avatar answered Nov 27 '25 07:11

Mats Petersson


Define a string with all the signs you want to search for:

std::string searchPunct=".,-;:'\"()?!"

Test eache single character of the of the input string, if it is member of searchPunct, by using std::string::find:

size_t countPunct( const char *s )
{
    static const std::string searchPunct = ".,-;:'\"()?!";
    size_t count = 0;
    for ( int i = 0; i < strlen( s ); i++ )
    {
        if ( searchPunct.find( s[i] ) != string::npos )
            count ++;
    }
    return count;
}
like image 45
Rabbid76 Avatar answered Nov 27 '25 06:11

Rabbid76