最近在学习C++编程,感觉很多东西经常使用到,但是每次查阅相关函数之后下次使用时还是不太记得,现在就对一些经常使用的string函数进行记录,以便自己在日后的查阅使用,近一步学习
std::string::find
查找字符串中的子串,如果查找到就返回子串第一次出现的位置pos,如果没有查找到就返回string::npos,表示已经查找到字符串长度的最大值,没有这个字符串。同时在查找字符串之后,一般使用判断语句和判断是不是string::npos,表示能否查找相应字符子串,
如:
string str ("There are two needles in this haystack with needles.");
string str2 ("needle");
std::size_t found = str.find(str2);//可以使用命名空间
if (found!=std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';
found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';
// let's replace the first needle:
str.replace(str.find(str2),str2.length(),"preposition");//替换字符串
std::cout << str << '\n';
Maximum value for size_t
npos is a static member constant value with the greatest possible value for an element of type
size_t.
This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string".
As a return value, it is usually used to indicate no matches.
This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.