2010-03-14 73 views
2

我如何在我的句子中找到'w'字符的第一個單詞。這個單詞可以出現在我的單詞的任何地方。例子的句子「Hi xyzwy ! 你在這裏做什麼?」所以結果應該是「xyzwy」。如何找到句子中有'w'的第一個單詞

+2

'提振:: regex'? – AraK 2010-03-14 08:44:48

+2

需要功課標籤嗎? – 2010-03-14 08:48:02

回答

3

從第一個字符開始,直到最後一個字符爲止。檢查你是否遇到'w'。如果是的話,直到你敲擊字詞分隔符(例如空格)或者到達字符串的開頭,然後打印所有字符,直到遇到另一個字詞分隔符(或字符串末尾)。

string Str; 
getline(cin, Str); 

for (int i = 0; i < Str.length(); ++i) 
    if (Str[i] == 'w') 
    { 
    // backtrack and print 
    break; 
    } 

或者使用String類的find method做搜索你,那麼你只需要確定這個詞。

1
boost::optional<std::string> 
find_word_with(std::string const& haystack, std::string const& needle) { 
    std::istringstream ss (haystack); 
    for (std::string word; ss >> word;) { 
    if (word.find(needle) != word.npos) { 
     return boost::optional<std::string>(word); 
    } 
    } 
    return boost::optional<std::string>(); 
} 

std::string const whitespace = " \t\r\n\v\f"; 
boost::optional<std::string> 
find_word_with2(std::string const& haystack, std::string const& needle) { 
    typedef std::string::size_type Pos; 

    Pos found = haystack.find(needle); 
    if (found == haystack.npos) { 
    return boost::optional<std::string>(); 
    } 

    Pos start = haystack.find_last_of(whitespace, found); 
    if (start == haystack.npos) start = 0; 
    else ++start; 

    Pos end = haystack.find_first_of(whitespace, found+1); 
    if (end == haystack.npos) end = haystack.length(); 

    return boost::optional<std::string>(haystack.substr(start, end - start)); 
} 

雙方對這些空白只單獨的單詞(我錯過了你想要的「xyzwy」,而不是「xyzwy!」在第一),但你可以修改它們忽略標點符號。第一個不太適合,但第二個可以很容易地修改爲使用find_first/last_ 而不是 _of與等效的正則表達式\w(「ABC..abc..012 .._」),而不是檢查空白。

請注意,第二個使用硬編碼的空白變量,由於流解決方案(它使用最後設置的全局語言環境)而不是區域意識,但它可能正是您想要的。

int main() { 
    { 
    boost::optional<std::string> r = 
     find_word_with("Hi xyzwy! what are you doing here?", "w"); 
    if (!r) std::cout << "not found\n"; 
    else std::cout << "found: " << *r << '\n'; 
    } 
    { 
    boost::optional<std::string> r = 
     find_word_with2("Hi xyzwy! what are you doing here?", "w"); 
    if (!r) std::cout << "not found\n"; 
    else std::cout << "found: " << *r << '\n'; 
    } 
    return 0; 
} 
1

如果你真的需要正則表達式,你可以使用

\w*w\w* 

例如:

#include <boost/regex.hpp> 
#include <string> 
#include <iostream> 
using namespace boost; 
using namespace std; 

int main() { 
    string s; 
    getline(cin, s); 
    match_results<string::const_iterator> m; 
    if (regex_search(s, m, regex("\\w*w\\w*"))) { 
     cout << "Found: " << string(m[0].first, m[0].second) << "\n"; 
    } else { 
     cout << "Not found\n"; 
    } 
    return 0; 
} 
相關問題