npos
Материал из cppreference.com
Синтаксис:
static const size_type npos = -1;
string::npos - это специальное значение, которое указывает на следующие ситуации:
- "не найдено", как возвращаемое значение функций find(), find_first_of(), и т.д.
- "все оставшиеся символы", в качестве длины подстроки.
Код для примера:
#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; // нахождение начала первого слова std::string::size_type beg_pos = text.find_first_not_of(delims); // пока beg_pos не равняется "not found" (т.е. найдено начало слова) while (beg_pos != std::string::npos) { // нахождение ограничителя (конца слова) end_pos = text.find_first_of(delims, beg_pos); // вставка подстроки в множество words.insert(text.substr(beg_pos, end_pos == std::string::npos // если end_pos равен "not found" ? std::string::npos // тогда "all remaining characters" : end_pos - beg_pos)); // нахождение начала слова beg_pos = text.find_first_not_of(delims, end_pos); } // вывод слов на экран std::copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, "\n")); return 0; }
Смотрите также: find, find_first_not_of, find_first_of, find_last_not_of, find_last_of, rfind, substr