什么是字符串::npos :
- 它是一个常量静态成员值,对于size_t类型的元素具有最高可能值。
- 它实际上意味着直到字符串。
- 它用作字符串成员函数中长度参数的值。
句法:
static const size_t npos = -1;
Where, npos is constant static value with the highest possible value for an element of type size_t and it is defined with -1.
程序 1:下面是 C++ 程序来说明字符串::npos的使用:
C++
// C++ program to demonstrate the use
// of string::npos
#include
using namespace std;
// Function that using string::npos
// to find the index of the occurrence
// of any string in the given string
void fun(string s1, string s2)
{
// Find position of string s2
int found = s1.find(s2);
// Check if position is -1 pr not
if (found != string::npos) {
cout << "first " << s2
<< " found at: "
<< int(found) << endl;
}
else
cout << s2 << " is not in"
<< "the string" << endl;
}
// Driver Code
int main()
{
// Given strings
string s1 = "geeksforgeeks";
string s2 = "for";
string s3 = "no";
// Function Call
fun(s1, s2);
return 0;
}
输出:
first for found at: 5
说明:在上面的程序字符串:npos常量定义为-1,因为size_t是无符号整数类型,-1是该类型的最大可能表示值。
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live