Comment analyser la chaîne complexe avec C ++?
Question
J'essaie de comprendre comment pourrais-je analyser cette chaîne en utilisant "sstream
"Et C ++
Le format de celui-ci est: "String, int, int".
J'ai besoin de pouvoir attribuer la première partie de la chaîne qui contient une adresse IP à une chaîne std ::.
Voici un exemple de cette chaîne:
std::string("127.0.0.1,12,324");
J'aurais alors besoin d'obtenir
string someString = "127.0.0.1";
int aNumber = 12;
int bNumber = 324;
Je mentionnerai à nouveau que je ne peux pas utiliser boost
bibliothèque, juste sstream
:-)
Merci
La solution
Voici une fonction de tokenisation utile. Il n'utilise pas de flux, mais peut facilement effectuer la tâche dont vous avez besoin en divisant la chaîne sur des virgules. Ensuite, vous pouvez faire ce que vous voulez avec le vecteur de jetons résultant.
/// 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;
}
Autres conseils
La C ++ String Toolkit Library (STRTK) A la solution suivante à votre problème:
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; }
Plus d'exemples peuvent être trouvés Ici
Ce n'est pas sophistiqué mais vous pouvez utiliser STD :: Getline pour diviser la chaîne:
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);
}
Ensuite, vous pouvez extraire les informations nécessaires de chacune des chaînes séparées.
Vous pourriez faire quelque chose comme ça aussi je crois (totalement du haut de ma tête, alors je m'excuse si je faisais des erreurs là-dedans) ...
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() );