重複の可能性:
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]