string类查找子串

.find

函数原型

size_t find ( const string& str, size_t pos = 0 ) const;
size_t find ( const char* s, size_t pos, size_t n ) const;
size_t find ( const char* s, size_t pos = 0 ) const;
size_t find ( char c, size_t pos = 0 ) const;

返回子串的起始索引位置

http://www.cplusplus.com/reference/string/string/find/

使用样例

#include <bits/stdc++.h>

using namespace std;

int main() {
	ios::sync_with_stdio(false);
	string a;
	string b;
	a = "qweqweqweq";
	b = "we";
	cout << a.find(b);//结果将输出1
	return 0;
}

.find_first_of

函数原型

size_t find_first_of ( const string& str, size_t pos = 0 ) const;
size_t find_first_of ( const char* s, size_t pos, size_t n ) const;
size_t find_first_of ( const char* s, size_t pos = 0 ) const;
size_t find_first_of ( char c, size_t pos = 0 ) const;

返回子串的起始索引位置

http://www.cplusplus.com/reference/string/string/find_first_of/

使用样例

#include <bits/stdc++.h>

using namespace std;

int main() {
	ios::sync_with_stdio(false);
	string a;
	string b;
	a = "123w456o";
	b = "wo";
	cout << a.find_first_of(b);//结果将输出3
	return 0;
}

与.find的区别: .find将会查找完整子串,而.find_first_of只会查找子串内元素在母串第一次出现的位置。

.find_last_of

函数原型

size_t find_last_of (const string& str, size_t pos = npos) const noexcept;
size_t find_last_of (const char* s, size_t pos = npos) const;
size_t find_last_of (const char* s, size_t pos, size_t n) const;
size_t find_last_of (char c, size_t pos = npos) const noexcept;

返回改子串的最后一个字符的索引位置

http://www.cplusplus.com/reference/string/string/find_last_of/

使用样例

#include <bits/stdc++.h>

using namespace std;

int main() {
	ios::sync_with_stdio(false);
	string a;
	string b;
	a = "123w456o";
	b = "wo";
	cout << a.find_last_of(b);//结果将输出7
	return 0;
}

从样例示范的输出结果可以得知.find_last_of与.find_first_of一样,都不是查找完整字串

posted @ 2020-09-19 14:40  琦桢  阅读(739)  评论(0编辑  收藏  举报