Sintaxe:
static const size_type npos = -1;
string::npos é um valor especial que indica:
find(), find_first_of(), etc.Exemplo de código:
#include <set> #include <iostream> #include <iterator> #include <algorithm> #include <string> int main() { const std::string text("Vectors contain contiguous elements stored as an array.\n\n" "Accessing members of a vector can be done in constant time, " "appending elements to a vector can be done in amortized constant time, " "whereas locating a specific value " "or inserting elements into the vector takes linear time."); const std::string delims(" \t\n.,?!;:\""); std::set<std::string> words; std::string::size_type end_pos; // encontrar inicio da primeira palavra std::string::size_type beg_pos = text.find_first_not_of(delims); // enquanto beg_pos não "não for encontrado" (ou seja, o início de uma palavra é encontrado) while (beg_pos != std::string::npos) { // encontrar delimitador (fim da palavra) end_pos = text.find_first_of(delims, beg_pos); // inserir substring em set words.insert(text.substr(beg_pos, end_pos == std::string::npos // se end_pos "não for encontrado" ? std::string::npos // então "todos os restantes caracteres" : end_pos - beg_pos)); // encontrar início da próxima palavra beg_pos = text.find_first_not_of(delims, end_pos); } // mostrar palavras std::copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, "\n")); return 0; }
Tópicos Relacionados: find, find_first_not_of, find_first_of, find_last_not_of, find_last_of, rfind, substr