zoukankan      html  css  js  c++  java
  • 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一样,都不是查找完整字串

  • 相关阅读:
    枚举-完美立方
    list
    undefined reference to `typeinfo for xxx 报错
    bubble排序
    Iframe跨域传值
    Iframe------父子页面传值
    LDAP 概念
    覆盖equals()要覆盖HashCode()
    HashSet和TreeSet的实现与原理
    jvm调优
  • 原文地址:https://www.cnblogs.com/RpgMaker/p/13696193.html
Copyright © 2011-2022 走看看