string find()函数、string::npos的含义、erase()函数
1. string::find()函数和string::npos函数的介绍
string::find()函数:是一个字符或字符串查找函数,该函数有唯一的返回类型,即string::size_type,即一个无符号整形类型,可能是整数也可能是长整数。
如果查找成功,返回按照查找规则找到的第一个字符或者子串的位置;
string::npos参数 —— npos 是一个常数,用来表示不存在的位置;
//如果字符串不存在包含关系,那么返回值就一定是npos
if(a.find(b)!=string::npos){
cout<<"yes"<<endl;
}else{
cout<<"no"<<endl;
}
string::size_type pos;
str.find(“字符串”) 返回值是字符在母串s中的下标位置;
str.find(“字符串”,9) 从s的下标9开始,查找字符串,返回字符串在s中的下标;
pos=s.find(str,pos) 查找s中str出现的所有位置。
pos=s.find_first_of(str) 返回str出现在母串s中的首次出现的位置
pos=s.find_last_of(str) 返回str出现在母串s中的最后一次出现的位置
#include<iostream>
#include<string>
using namespace std;
int main(){
string s("abcbcdcd");
string str="cd";
string::size_type pos;
pos=s.find("bc");
if(pos!=s.npos){
cout<<pos<<endl;//1
}else{
cout<<"no"<<endl;
}
pos=s.find("bc",2);
cout<<"从s下标2开始查找:"<<pos<<endl;//3
int i=1;
while((pos=s.find(str,pos))!=string::npos){
cout<<"位置"<<i<<":"<<pos<<endl;//位置1:4 位置2:6
pos++;
i++;
}
cout<<"第一次:"<<s.find_first_of('d')<<endl;//5
cout<<"最后一次:"<<s.find_last_of('d')<<endl;//7
}
2 erase()函数
erase函数的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );
(2)iterator erase ( iterator position );
(3)iterator erase ( iterator first, iterator last );
也就是说有三种用法:
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);删除position处的一个字符(position是个string类型的迭代器)
(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)
#include<iostream>
#include<string>
using namespace std;
int main(){
string s("I love zufe.");
string::iterator it;
s.erase(1,5);//删除从1开始的5个字符
cout<<s<<endl;//I zufe.
it=s.begin()+6;
s.erase(it);//删除位置为9的字符
cout<<s<<endl;//I zufe
s.erase(s.begin()+3,s.end()-2);//删除之间的字符
cout<<s<<endl;//I zfe
}
3 字符串截取 s.substr()
substr有2种用法:
假设:string s = “0123456789”;
string sub1 = s.substr(5); //只有一个数字5表示从下标为5开始一直到结尾:sub1 = “56789”
string sub2 = s.substr(5, 3); //从下标为5开始截取长度为3位:sub2 = “567”
4 字符是否为数字 isdigit©
isdigit©是C语言中的一个函数,
isdigit()在ctype.h头文件中声明。
用于检查输入的字符是否为数字字符[0-9]。
如果是数字,则返回非零值,否则返回0。
cout << isdigit('9'); // Output: 1
#include <cctype>
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "hj;pq910js4";
int check;
cout << "The digit in the string are:" << endl;
for (int i = 0; i < strlen(str); i++) {
// check if str[i] is a digit
check = isdigit(str[i]);
if (check)
cout << str[i] << endl;
}
return 0;
}
输出
The digit in the string are:
9
1
0
4
5 n进制字符串转十进制 stoi(s)
使用之前要包含头文件#include< string >
(stoi就是string to int 的缩写)
stoi(字符串,起始位置,几进制);
stoi(str),将数字字符转化位int输出;
string str = "111111";
int a = stoi(str);
cout << a << endl;//输出111111