2010-03-14 74 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; 
} 
相关问题