【问题标题】:C++ Check that in a string only exist following charactersC ++检查字符串中是否仅存在以下字符
【发布时间】:2014-03-17 10:18:36
【问题描述】:

有效的字符是

// ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/

#include <iostream>
#include <string>

using namespace std;

int main();
{
  bool bIsValid = true;

  // test characters
  string strCheck("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/");
  string s("foo@?+baa") ; // should bring a "false" because of the "@?+" characters

  string::const_iterator it = strCheck.begin();

   // this is NOT a clever soulution has anybody a better idea ?   
   while (s.find(*it) != string::npos) 
   {
     ++it;

     if(!s.find((*it))
     {
       bIsValidKey = false;
       break;
     }

   }

cout << "Is Valid: " << bIsValid << endl ;

}

我的问题是如何获取迭代器点之后的第一个字符进行比较 具有允许的字符。我需要像 (*it).first_charater_after 这样的东西 解决问题。

是否有人有其他想法来检查字符串中是否仅存在已定义的 字符数?

【问题讨论】:

  • 请修复if(!s.find((*it)))
  • 带括号的 if(!s.find((*it))) 的问题在哪里?我知道必须有 (*it).somthing() 但是什么?
  • 我建议你看看正则表达式库:cplusplus.com/reference/regex 或 google c++ rexexp。它可能需要一些学习,但一旦掌握它可以节省大量时间。
  • 是个好主意,我会看到的。
  • 我发布了一个使用正则表达式的示例。它非常灵活,您不必输入所有有效字符

标签: c++ string iterator compare


【解决方案1】:

使用string::find_first_not_of?

【讨论】:

    【解决方案2】:

    试试这个:

    #include <iostream>
    #include <string>
    #include <regex>
    
    using namespace std;
    
    int main()
    {
      bool bIsValid = true;
    
      string s("GHHbaa111__") ; // Add/remove other characters
    
        regex r("^[[:alnum:]_]*$");
    
        if (regex_match(s,r)) {
            cout << "Valid string" << endl;
        } else {
            cout << "Invalid string" << endl;
        }
    
     }
    

    【讨论】:

      【解决方案3】:
      #include <iostream>
      #include <string>
      
      int main() {
        bool bIsValid = true;
      
        // test characters
        std::string strCheck("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/");
        std::string s("foo@?+baa") ; // should bring a "false" because of the "@?+" characters
      
        if (s.find_first_not_of(strCheck) != std::string::npos)
          bIsValid = false;
      
        std::cout << "Is Valid: " << bIsValid << std::endl ;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-28
        • 1970-01-01
        • 2012-05-25
        • 1970-01-01
        • 2016-03-27
        • 1970-01-01
        • 2023-03-14
        • 2020-07-16
        相关资源
        最近更新 更多