Come analizzare la stringa complessa con C ++?
Domanda
Sto cercando di capire come potrei analizzare questa stringa usando "sstream
"E C ++
Il formato di esso è: "String, int, int".
Devo essere in grado di assegnare la prima parte della stringa che contiene un indirizzo IP a una stringa std ::.
Ecco un esempio di questa stringa:
std::string("127.0.0.1,12,324");
Avrei quindi bisogno di ottenere
string someString = "127.0.0.1";
int aNumber = 12;
int bNumber = 324;
Menzionerò di nuovo che non posso usare boost
Biblioteca, solo sstream
:-)
Grazie
Soluzione
Ecco un'utile funzione di tokenizzazione. Non usa i flussi, ma può facilmente eseguire l'attività necessaria dividendo la stringa nelle virgole. Quindi puoi fare quello che vuoi con il vettore risultante di token.
/// 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;
}
Altri suggerimenti
Il Libreria di strumenti String C ++ (STRTK) Ha la seguente soluzione al tuo problema:
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; }
Altri esempi possono essere trovati Qui
Non è elegante ma puoi usare std :: getline per dividere la stringa:
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);
}
Quindi è possibile estrarre le informazioni necessarie da ciascuna delle stringhe separate.
Potresti fare qualcosa di simile anche a questo credo (totalmente dalla parte superiore della mia testa, quindi mi scuso se ho fatto degli errori lì dentro) ...
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() );