string find函数

本文深入探讨了C++标准库中的std::string成员函数find,包括其用法、参数、返回值以及常见应用案例。通过实例解析,帮助读者掌握如何在字符串中查找子串并定位其位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



概述
c++中string的find函数大致可以有:find(),rfind(),find_first_of(),find_last_of(),find_first_not_of(),find_last_not_of()这六种。接下来我将从这六个方法进行展开介绍。

详解

find()函数
  • 函数原型:
//string (1)
size_type find (const basic_string& str, size_type pos = 0) const noexcept;
//c-string (2)
size_type find (const charT* s, size_type pos = 0) const;
//buffer (3)
size_type find (const charT* s, size_type pos, size_type n) const;
//character (4)
size_type find (charT c, size_type pos = 0) const noexcept;

  • 原型解释(假设ss为调用函数的string变量)
    • 原型1.
    • 从ss中位置为pos处开始查找字符串str。pos默认为0;
    • 原型2
    • 从ss中位置为pos出开始查找指针s所指向的字符串。pos默认为0;
    • 原型3
    • 从ss中位置为pos出开始查找指针s所指向数组的前n个字符。pos与n都没有默认值;
    • 原型4
    • 从ss中位置为pos处开始查找字符c。pos默认为0;
  • 范例

int main()
{
string str("babccbabcaabcccbabccabcabcabbabcc");
//1.size_type find (const basic_string& str, size_type pos = 0) const noexcept;
string tem = "abc";
cout << str.find(tem) << endl; //1
cout << str.find(tem, 2) << endl; //6

//2.size_type find (charT c, size_type pos = 0) const noexcept;
cout << str.find(‘c’) << endl; //3
cout << str.find(‘c’, 4) << endl; //4

//3.size_type find
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值