簡體   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