2

「w」文字を含む文の最初の単語を見つけるにはどうすればよいですか.この文字は単語のどこにでも存在する可能性があります.文の例「こんにちは xyzwy! ここで何をしていますか?」したがって、結果は「xyzwy」になるはずです。

4

3 に答える 3

3

最初の文字から最後の文字まで文字列を調べます。「w」に遭遇したかどうかを確認してください。はいの場合は、単語の区切り記号 (スペースなど) に到達するか、文字列の先頭に到達するまでバックトラックし、別の単語の区切り記号 (または文字列の末尾) に到達するまですべての文字を出力します。

string Str;
getline(cin, Str);

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

または、文字列クラスのfind メソッドを使用して検索を行い、単語を特定するだけです。

于 2010-03-14T08:49:47.153 に答える
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;
}
于 2010-03-14T09:58:55.593 に答える
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」が必要だったことを見逃していました) が、句読点を無視するように変更できます。最初のものはあまり受け入れられませんが、2番目のものは、空白をチェックする代わりに正規表現 ("ABC..abc..012.._") に相当するものでfind_first/last_ not _ofを使用するように簡単に変更できます。\w

ハードコードされた空白変数を使用する 2 番目は、ストリーム ソリューション (最後に設定されたグローバル ロケールを使用する) のようにロケールを認識しないことに注意してください。

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;
}
于 2010-03-14T09:29:47.247 に答える