12

sstream" " と C++を使用してこの文字列を解析する方法を見つけようとしています。

形式は「string,int,int」です。

IP アドレスを含む文字列の最初の部分を std::string に割り当てることができる必要があります。

この文字列の例を次に示します。

std::string("127.0.0.1,12,324");

次に、取得する必要があります

string someString = "127.0.0.1";
int aNumber = 12;
int bNumber = 324;

boostライブラリを使用できないことをもう一度述べますsstream:-)

ありがとう

4

4 に答える 4

13

C ++文字列ツールキットライブラリ(Strtk)には、問題に対する次の解決策があります。

int main()
{{
   std :: string data( "127.0.0.1,12,324");
   文字列someString;
   int aNumber;
   int bNumber;
   strtk :: parse(data、 "、"、someString、aNumber、bNumber);
   0を返します。
}

その他の例はここにあります

于 2010-01-15T19:24:58.087 に答える
6

派手ではありませんが、std::getlineを使用して文字列を分割できます。

std::string example("127.0.0.1,12,324");
std::string temp;
std::vector<std::string> tokens;
std::istringstream buffer(example);

while (std::getline(buffer, temp, ','))
{
    tokens.push_back(temp);
}

次に、分離された各文字列から必要な情報を抽出できます。

于 2010-01-15T16:33:28.333 に答える
3

これは便利なトークン化関数です。ストリームは使用しませんが、文字列をカンマで分割することにより、必要なタスクを簡単に実行できます。その後、結果として得られるトークンのベクトルを使用して、好きなことを行うことができます。

/// String tokenizer.
///
/// A simple tokenizer - extracts a vector of tokens from a 
/// string, delimited by any character in delims.
///
vector<string> tokenize(const string& str, const string& delims)
{
    string::size_type start_index, end_index;
    vector<string> ret;

    // Skip leading delimiters, to get to the first token
    start_index = str.find_first_not_of(delims);

    // While found a beginning of a new token
    //
    while (start_index != string::npos)
    {
        // Find the end of this token
        end_index = str.find_first_of(delims, start_index);

        // If this is the end of the string
        if (end_index == string::npos)
            end_index = str.length();

        ret.push_back(str.substr(start_index, end_index - start_index));

        // Find beginning of the next token
        start_index = str.find_first_not_of(delims, end_index);
    }

    return ret;
}
于 2010-01-15T16:26:07.487 に答える
2

あなたもこのようなことをすることができると私は信じています(完全に頭から離れているので、そこでミスをした場合はお詫びします)...

stringstream myStringStream( "127.0.0.1,12,324" );
int ipa, ipb, ipc, ipd;
char ch;
int aNumber;
int bNumber;
myStringStream >> ipa >> ch >> ipb >> ch >> ipc >> ch >> ipd >> ch >> aNumber >> ch >> bNumber;

stringstream someStringStream;
someStringStream << ipa << "." << ipb << "." << ipc << "." << ipd;
string someString( someStringStream.str() );
于 2010-01-15T16:30:12.597 に答える