【C++笔记】find函数的用法

简介

C++中可以利用 .find()函数返回字符/字符串的索引(位置)

用法

1. 检索字符串

基本形式:str1.find(str2)
返回值:返回str2中首个字符在str1中的地址

#include <iostream> 
using namespace std;

int main(){
	
	int i;
	string str1 = "ers";
	string str2 = "university";
	char c = 'n';
	
	i = str2.find(str1);
	cout << "i = " << i;
}

输出:
在这里插入图片描述

2.检索字符

基本形式:str.find(char)
返回值:返回str中c的索引

#include <iostream> 
using namespace std;

int main(){
	
	int i;
	string str1 = "ers";
	string str2 = "university";
	char c = 'n';
	
	i = str2.find(c);
	cout << "i = " << i;
}

输出:
在这里插入图片描述

例题

1.子串主串1

编写一个c++程序,接受来自用户的字符串和单个字符。程序应该确定字符包含在字符串中的次数。(提示:使用find(str, int)函数搜索字符串。这个函数应该在一个循环中使用)

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

int main(){
	int index = 0;	//下标 
	int count = 0;	//次数 
	
	string str,sub;
	cout<<"主串:";
	getline(cin,str);	
	cout<<"子串:";
	getline(cin,sub);

	while( (index = str.find(sub,index)) < str.length() ){
		count++;
		index++;
	}
	
	cout << "The number of substrings is " << count << endl;
}

2.子串主串2

计算子字符串(子串)在主字符串(主串)中出现的次数。

#include<iostream>
#include<string>
using namespace std;
int main() {
	string str;
	char c;
	//输入字符串 
	cout << "请输入一个字符串:"; 
	cin >> str;
	//输入单个字符 
	cout << "请输入一个字符:";
	cin >> c;
	 
	int count = 0;
	int position = 0;
	int i = 1;
	while( ( position = str.find(c,position) ) < str.size()){
		cout << "位置 " << i << ": " << position + 1 << endl;
		position ++;
		i ++;
		count ++;
	}
	cout << c << "一共出现了" << count << "次";
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

调参侠鱼尾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值