Gol*_*les 12 c++ string sstream
我试图找出如何使用" sstream"和C++ 解析这个字符串
它的格式是:"string,int,int".
我需要能够将包含IP地址的字符串的第一部分分配给std :: string.
以下是此字符串的示例:
std::string("127.0.0.1,12,324");
Run Code Online (Sandbox Code Playgroud)
然后我需要获得
string someString = "127.0.0.1";
int aNumber = 12;
int bNumber = 324;
Run Code Online (Sandbox Code Playgroud)
我会再次提到我不能使用boost库,只是sstream:-)
谢谢
小智 13
在C++字符串工具箱库(Strtk)具有以下问题的解决方案:
int main()
{
std::string data("127.0.0.1,12,324");
string someString;
int aNumber;
int bNumber;
strtk::parse(data,",",someString,aNumber,bNumber);
return 0;
}
更多例子可以在这里找到
它不是花哨但你可以使用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);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以从每个分离的字符串中提取必要的信息.
这是一个有用的标记化函数。它不使用流,但可以通过用逗号分割字符串来轻松执行您所需的任务。然后你可以用得到的标记向量做任何你想做的事情。
/// 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2045 次 |
| 最近记录: |