0

重複の可能性:
C++ での文字列の分割

私は私の質問で得た答えの1つからこのベクトル関数を持っています

vector<string> split(const string& s, char delim)
{
  vector<string> elems(2);
  string::size_type pos = s.find(delim);
  elems[0] = s.substr(0, pos);
  elems[1] = s.substr(pos + 1);
  return elems;
}

ただし、2 つの要素しか受け入れません。文字列 s に存在する区切り文字 s の数に基づいて受け入れるように変更するにはどうすればよいですか?

たとえば、これがある場合:

user#password#name#fullname#telephone

場合によってはサイズが異なる場合があります。

この関数を要素の数に関係なく柔軟に機能させ、上記のこの関数のように分割できるようにするにはどうすればよいですか?

私の問題をさらに説明するために:

私が達成したいのは、このベクトル関数を使用して、同じ区切り文字をサイズ 2 に固定する代わりに N サイズに分割する機能です。

この関数は、文字列内の最大 2 つの要素のみを分割できます。それを超えると、セグメンテーション コア ダンプが発生します

以前のように、次のような使用法のみが必要です

user:pass

属性を追加したので、分割できるようにする必要があります

user:pass:name:department

x[2] と x[3] はそれぞれ名前と部門を返します

それらはすべて同じ区切り文字を使用します。

更なるアップデート:

以下の回答の1が提供するこの機能を使用してみました

vector<string> split(const string& s, char delim)
{
bool found;
vector<string> elems;
  while(1){
   string::size_type pos = s.find(delim);
   if (found==string::npos)break;
   elems.push_back(s.substr(0, pos));
   s=s.substr(pos + 1);
  }
  return elems;
}

そして、私はいくつかのエラーが発生します

server.cpp: In function ‘std::vector<std::basic_string<char> > split(const string&, char)’:
server.cpp:57:22: error: passing ‘const string {aka const std::basic_string<char>}’ as ‘this’ argument of ‘std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>, std::basic_string<_CharT, _Traits, _Alloc> = std::basic_string<char>]’ discards qualifiers [-fpermissive]
4

3 に答える 3

1

このようなもの %)

  vector<string> elems;
  while(1){
   string::size_type pos = s.find(delim);
   if (found==string::npos)break;
   elems.push_back(s.substr(0, pos));
   s=s.substr(pos + 1);
  }
  if(s.size())elems.push_back(s);
  return elems;
于 2012-08-12T08:21:38.823 に答える
0

さて、あなたが知っている、メンバー関数をチェックしてくださいpush_back

于 2012-08-12T08:04:03.397 に答える
0

一般的な分割機能を提供するほぼ重複に対する1つの答えがあります。

std::vector<std::string> split(std::string const& str, std::string const& delimiters = "#") {
  std::vector<std::string> tokens;

  // Skip delimiters at beginning.
  string::size_type lastPos = str.find_first_not_of(delimiters, 0);
  // Find first "non-delimiter".
  string::size_type pos = str.find_first_of(delimiters, lastPos);

  while (string::npos != pos || string::npos != lastPos) {
    // Found a token, add it to the vector.
    tokens.push_back(str.substr(lastPos, pos - lastPos));
    // Skip delimiters.  Note the "not_of"
    lastPos = str.find_first_not_of(delimiters, pos);
    // Find next "non-delimiter"
    pos = str.find_first_of(delimiters, lastPos);
  }
  return tokens;
}

これは次のように簡単にラップできます。

std::vector<std::string> split(std::string const& str, char const delimiter) {
  return split(str,std::string(1,delimiter));
}
于 2012-08-12T08:26:18.073 に答える