using str::find and find_first_of and last_of

using str::find and find_first_of and last_of

本文关键字:of find and last str first using      更新时间:2023-10-16

我不确定我是否正确使用了find_first_of和last_of,但是我想做的是,我需要打印错误时在代码的开头还是在代码末尾找到错误,另外,当它找到两个或多个_接下来的两个或多个,例如此lol___, lol__lol, _lol_, _lol, lol_,和另一条规则,_不能在大写字母面前,例如此lol_Lol

这是我的代码

             std::string::size_type n;
             std::string::size_type n2;
             std::string::size_type n3;
             std::string const ss = slovo;
             n  = ss.find('_');
             n2 = ss.find_first_of('_');
             n3 = ss.find_last_of('_');
            if (n2 == std::string::npos && n3 == std::string::npos) {
            cout << "chyba" << endl;
            }else if(n == std::string::npos){
                  string s = transform(slovo);
                  cout << s << endl;
                  }else{
                  string s = untransform(slovo);
                  cout << s << endl;
                  }

编辑>

if ( !ss.empty() && ss.front() == '_' && ss.back() == '_' )
               {
                cout << "Chyba" << endl;
               } else {
                if ( ss.length() > 3 && ss.find( '__', 1, ss.length() - 2 ) != std::string::npos )
                {
                 if (n == std::string::npos){
                      string s = transform(slovo);
                      cout << s << endl;
                      }else{
                      string s = untransform(slovo);
                      cout << s << endl;
                      }
                }else{
            cout << "chyba" << endl;
         } 
         }

edit2:

cin >> slovo;
             }      
             std::string::size_type n;
             std::string const ss = slovo;
             n  = ss.find('_');
             // kontrola podtrznika
           if ( ss.empty() && ss[0] == '_' && ss[ss.length() - 1] == '_' )
           {
            cout << "chyba" << endl;
            }
           if ( ss.length() > 3 && ss.find( "__", 1, ss.length() - 2 ) != std::string::npos )
           {
            cout << "chyba" << endl;
            }
             if (n == std::string::npos)
                 {
                  string s = transform(slovo);
                  cout << s << endl;
                  }else{
                  string s = untransform(slovo);
                  cout << s << endl;
                 }

如果这些函数返回 npos,则表示字符中找不到字符。因此,如果其中一个返回,所有三个都将。

因此,此代码输出" chyba",字符串中没有_或否则调用untransform。从您的描述中,这不是您打算的。

您确实需要在所有这些条件下扫描字符串。如果要检查字符串的第一个和最后一个字符,请使用ss[0]ss[ss.length() - 1](按照适当的护理,您没有长度为0或1的字符串)。

很明显,两个函数调用将为您提供相同的结果

         n  = ss.find('_');
         n2 = ss.find_first_of('_');

在这种情况下它们是等效的。

如果我正确理解了您,您需要确定字符串中的第一个字符和最后一个字符是否强,字符串是否包含两个相邻的Undestores本身。

要确定第一种情况,很容易编写

if ( !ss.empty() && ss.front() == '_' && ss.back() == '_' )
{
//...
} 

找到至少两个相邻的下划线,不包括您可以写的第一个和最后一个字符

if ( ss.length() > 3 && ss.find( "__", 1, ss.length() - 2 ) != std::string::npos )
{
//...
}