简体   繁体   中英

How to check if a string contains punctuation c++

I am attempting to iterate over a string to check for punctuation. I've tried to use ispunct() but am receiving an error that there is no matching fucntion for call to ispunct. Is there a better way to implement this?

for(std::string::iterator it = oneWord.begin(); it != oneWord.end(); it++)
{
    if(ispunct(it))
    {
    }
}

it is an iterator, it points to a character in a string. You have to dereference it to get the thing it points to.

if(ispunct(static_cast<unsigned char>(*it)))

Is there a better way to implement this?

Use std::any_of :

#include <algorithm>
#include <cctype>
#include <iostream>

int main()
{
   std::string s = "Contains punctuation!!";
   std::string s2 = "No puncuation";
   std::cout << std::any_of(s.begin(), s.end(), ::ispunct) << '\n';
   std::cout << std::any_of(s2.begin(), s2.end(), ::ispunct) << '\n';
}

Live Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM