下面的代码中演示了string类型的成员函数substr/find及成员变量npos的用法。
1、substr: 用于截断字符串,找出对应位置的子串
2、find: 用于查询字符串中的指定内容
3、npos: 一个常数,用以作为find函数为查询到时的匹配值
这两个函数及变量是平时使用中经常会用到的,因此特此记录其用法。
以下是源代码:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
str = "123456789";
// substr的用法
cout << str.substr(3, 4) << endl; // 4567 输出从位置3开始,长度为4的子串
cout << str.substr(3) << endl; // 456789 输出位置3及后面的所有字符
// find 及 npos 的用法
int pos = str.find("10");
if (pos == string::npos)
{
cout << "not found! " << endl;
}
// str.find(str2,pos) 表示从pos的位置开始查找
if (str.find("9", 8) != str.npos)
{
cout << "find it!" << endl;
}
return 0;
}
代码输出:
4567
456789
not found!
find it!
谢谢阅读