【问题标题】:How do I find a complete word (not part of it) in a string in C++如何在 C++ 中的字符串中找到一个完整的单词(不是它的一部分)
【发布时间】:2014-03-19 19:40:01
【问题描述】:

在 C++ 代码中,我试图在一个句子中搜索一个词,但它一直在进行部分搜索。我希望它只搜索完整的单词而不是它的一部分,有什么帮助吗?

size_t kk;
string word="spo";
string sentence="seven spoons";

kk=sentence.find(word);
if (kk !=string::npos)
cout << "something" << endl;

【问题讨论】:

    标签: c++ string find


    【解决方案1】:

    听起来你想要的东西是由正则表达式中的单词边界或单词字符的概念来处理的。

    这是一个只返回完整匹配的程序。也就是说,只有当该词与您正在搜索的确切词完全匹配时,它才会返回一个词。如果sentence 中的某个单词将您的目标单词作为严格的子字符串,那么它将不会被返回。

    #include <regex>
    #include <string>
    #include <iostream>
    
    int main() {
      std::string word = "spo"; // spo is a word?
      std::string sentence = "seven spoons";
    
      std::regex r("\\b" + word + "\\b"); // the pattern \b matches a word boundary
      std::smatch m;
    
      if (std::regex_search(sentence, m, r)) { // this won't find anything because 'spoons' is not the word you're searching for
        std::cout << "match 1: " << m.str() << '\n';
      }
    
      sentence = "what does the word 'spo' mean?";    
      if (std::regex_search(sentence, m, r)) { // this does find the word 'spo'
        std::cout << "match 2: " << m.str() << '\n';
      }
    }
    

    或者,也许您的意思是要查找与您正在搜索的部分单词匹配的任何单词。正则表达式也可以做到这一点:

      std::string partial_word = "spo";
      std::regex r("\\w*" + partial_word + "\\w*"); // the pattern \w matches a word character
    

    这会产生:

    match 1: spoons
    match 2: spo
    

    【讨论】:

    • 如果搜索词是“七”(存在,但前面没有空格)或“勺子”(存在,但后面没有空格)怎么办? )?
    • @FredLarson 单词边界的定义说明了这一点。它有效。
    • 啊,明白了。为你 +1。
    【解决方案2】:

    这里有很多选项:

    a) 搜索[space]WORD[space] 而不仅仅是WORD

    string word="spo";
    string sentence="seven spoons";
    kk=sentence.find(" "+word+" ");
    

    请注意,如果您的单词由换行符或其他空格分隔,这将不起作用。

    b) 将字符串拆分为单词,将它们存储在vector 中,并使用std::find 检查所需单词是否在向量中。

    stringstream parser(sentence);
    istream_iterator<string> start(parser);
    istream_iterator<string> end;
    
    vector<string> words(start, end);
    if(find(words.begin(), words.end(), word)!=words.end()) cout<<"found!";
    

    如果您要经常搜索单词,这可能是最佳选择,因为您可以将向量存储在某处以供将来参考,因此您不必拆分它。另外 - 如果你想让它工作,一定要#include &lt;algorithm&gt;#include &lt;vector&gt;

    c) 搜索单词并检查是否isspace(string[position-1]) &amp;&amp; isspace(string[position+wordLength])

    string word="spo";
    string sentence="seven spoons";
    kk=sentence.find(" "+word+" ");
    if(kk!=string::npos){
        if((kk==0 || isspace(sentence[kk-1])) && (kk+word.length()==sentence.length() || isspace(kk+word.length()+1)))
           cout << "found!";
    }
    

    【讨论】:

    • 不错且实用的答案!即使是几年前,答案 c) 也包含错误。应该是:if((kk==0 || isspace(sentence[kk-1])) &amp;&amp; (kk+word.length()==sentence.length() || isspace(sentence[kk+word.length()])))
    【解决方案3】:

    类似这样的:

    std::size_t kk;
    std::string word="spoo";
    std::string sentence="seven spoons tables";
    
    std::stringstream ss(sentence) ;
    std::istream_iterator<std::string> f ;
    
    auto it =std::find_if(  std::istream_iterator<std::string> (ss),
                            f,
                            [=](const std::string& str){
                            return str == word;
                            }
     );
    
    if(it != f )
     std::cout << "Success" <<std::endl;
    

    here

    【讨论】:

      【解决方案4】:

      我认为最好的方法是split your string 使用空格和标点符号作为分隔符,然后在结果上使用std::find

      #include <boost/algorithm/string.hpp>
      #include <vector>
      #include <string>
      #include <algorithm>
      
      int main()
      {
          std::string word="spo";
          std::string sentence="seven spoons";
          std::vector<std::string> words;
          boost::split(words, sentence, boost::is_any_of("\n\t .,!?\"()"));
          auto match = std::find(begin(words), end(words), word);
          if (match != end(words))
          {
              // Found it!
          }
          else
          {
              // Not there.
          }
       }
      

      【讨论】:

        【解决方案5】:
        string word="spo";  
        string sentence="seven spoons";  
        
        string::size_type nIndex = sentence.find( word, 0 );  
        if( nIndex != string::npos )  
        {  
        if ((nIndex + word.length() + 1) == sentence.length())  
        {  
            cout << "Found" << endl;  
        }  
        else  
        {  
        string::size_type nSpace = sentence.find( " ", nIndex );  
        if (nSpace == (nIndex + word.length()))  
        {  
        cout << "Found" << endl;  
        }  
        }  
        }  
        else  
        {  
        cout << "No Match" << endl;  
        }  
        

        【讨论】:

          【解决方案6】:

          这似乎奏效了。

          #include <string>
          
          /*find word in sentence and return the index of first occurrence*/
          int find_whole(string sentence,string word){
              size_t pos=sentence.find(word);
              size_t offset=pos+sentence.size()+1;
          
              if((pos!=string::npos) && (sentence.substr(pos,offset)==word))
                  return pos;
              return string::npos;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-01-05
            • 2020-03-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-06-05
            相关资源
            最近更新 更多