繁体   English   中英

如何检查字符串是否包含标点符号

[英]How to check if a string contains punctuation c++

我试图遍历字符串以检查标点符号。 我尝试使用ispunct(),但收到一个错误,提示没有匹配的功能调用ispunct。 有没有更好的方法来实现这一目标?

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

it是一个迭代器,它指向字符串中的字符。 您必须取消引用它才能得到它指向的内容。

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

有没有更好的方法来实现这一目标?

使用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';
}

现场例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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