C++字符串的查找

关于字符串的各种查找

原文出处:https://www.cnblogs.com/yongpan/p/7920165.html

 

1 find函数:在字符串中查找子字符串中出现的位置

  1. 函数最终返回的是子字符串出现在字符串中的起始下标
  2. 该函数有两个参数,第一个参数是待查找的子字符串
  3. 第二个参数是表示开始查找的位置(默认从0开始查找)
#include <iostream>
#include <string>
using namespace std;

int main() {
	string s1 = "first second third";
	string s2 = "second";
	int index = s1.find(s2,0);
	if(index < s1.length())
		cout<<"Found at index : "<< index <<endl;
	else
		cout<<"Not found"<<endl;
	return 0;
}

 输出结果为:Found at index : 6

 

rfind函数:在字符串中查找子字符串

  1. 与find函数不同的是最多查找到第二个参数处
  2. 如果到了第二个参数所指定的下标还没有找到子字符串,则返回一个无穷大值
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "first second third";
    string s2 = "second";
    int index = s1.rfind(s2,6);
    if(index < s1.length())
        cout<<"Found at index : "<< index <<endl;
    else
        cout<<"Not found"<<endl;
    return 0;
}

 输出结果为:Found at index : 6

 

find_first_of函数:查找子字符串和字符串共同具有的字符在字符串中出现的位置

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "first second second third";
    string s2 = "asecond";
    int index = s1.find_first_of(s2);
    if(index < s1.length())
        cout<<"Found at index : "<< index <<endl;
    else
        cout<<"Not found"<<endl;
    return 0;
}

4 find_first_not_of函数:查找在s1字符串但不在s2字符串中的首位字符的下标

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1 = "secondasecondthird";
    string s2 = "asecond";
    int index = s1.find_first_not_of(s2);
    if(index < s1.length())
        cout<<"Found at index : "<< index <<endl;
    else
        cout<<"Not found"<<endl;
    return 0;
}

 

### C++ 中 `string` 类型查找子串方法 在 C++ 的标准库中,`std::string` 提供了多种成员函数来处理字符串操作。其中最常用的查找子串的方式是通过 `find` 函数实现。 #### 使用 `find` 成员函数 `find` 函数用于定位一个子串首次出现的位置。该函数接受两个参数:要查找的子串以及起始位置(可选)。如果找到了匹配项,则返回其索引;如果没有找到,则返回 `std::string::npos` 值[^1]。 下面是一个具体的实例展示如何利用此功能: ```cpp #include <iostream> #include <string> int main() { std::string source = "testcodecodecode"; std::string target1 = "code"; std::string target2 = "lee"; size_t pos1 = source.find(target1); size_t pos2 = source.find(target2); if (pos1 != std::string::npos) { std::cout << "Found '" << target1 << "' at position: " << pos1 << '\n'; } else { std::cout << "'" << target1 << "' not found.\n"; } if (pos2 != std::string::npos) { std::cout << "Found '" << target2 << "' at position: " << pos2 << '\n'; } else { std::cout << "'" << target2 << "' not found.\n"; } } ``` 这段代码会输出如下内容: ``` Found 'code' at position: 4 'lee' not found. ``` 此外还有其他几个类似的成员函数可以用来执行更复杂的模式匹配任务,比如 `rfind`, 它是从右向左搜索给定子串的第一个出现位置;而 `find_first_of` 和 `find_last_of` 则分别用于寻找任意字符集合内的最早或最后一位所在之处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值