简介
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;
}