主要涉及到string类的两个函数find和substr:
find()函数的用法:
原型:size_t find ( const string& str, size_t pos = 0 ) const;
功能:查找子字符串第一次出现的位置。
参数说明:str为子字符串,pos为初始查找位置。
返回值:找到的话返回第一次出现的位置,否则返回string::npos
//find函数返回类型 size_type
string s("1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i");
string flag;
string::size_type position;
//find 函数 返回jk 在s 中的下标位置
position = s.find("jk");
if (position != s.npos) //如果没找到,返回一个特别的标志c++中用npos表示,我这里npos取值是4294967295,
{
cout << "position is : " << position << endl;
}
else
{
cout << "Not found the flag" + flag;
}
//find 函数 返回flag 中任意字符 在s 中第一次出现的下标位置
flag = "c";
position = s.find_first_of(flag);
cout << "s.find_first_of(flag) is : " << position << endl;
//从字符串s 下标5开始,查找字符串b ,返回b 在s 中的下标
position=s.find("b",5);
cout<<"s.find(b,5) is : "<<position<<endl;
//查找s 中flag 出现的所有位置。
flag="a";
position=0;
int i=1;
while((position=s.find_first_of(flag,position))!=string::npos)
{
//position=s.find_first_of(flag,position);
cout<<"position "<<i<<" : "<<position<<endl;
position++;
i++;
}
//查找flag 中与s 第一个不匹配的位置
flag="acb12389efgxyz789";
position=flag.find_first_not_of (s);
cout<<"flag.find_first_not_of (s) :"<<position<<endl;
//反向查找,flag 在s 中最后出现的位置
flag="3";
position=s.rfind (flag);
cout<<"s.rfind (flag) :"<<position<<endl;
}
substr()函数用法:
功能:获得子字符串
返回值:子字符串
string a=s.substr(0,5); 从第0位开始的长度为5的字符串.默认时的长度为从开始位置到尾
string字符串分割,并把子字符串放入数组:
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
vector<string> fenge1(string a,char c)
{
vector<string> b;
int pos=0,i,len=a.length();
for(i=0;i<len;i++)
{
if(i==0&&a[i]==c)
pos=i+1;
else if(a[i]==c)
{
b.push_back(a.substr(pos,i-pos));
pos=i+1;
}
else if(i==len-1)
{
b.push_back(a.substr(pos,i-pos+1));
}
}
return b;
}
vector<string> fenge2(string a,char c)
{
a=a+c;
int i,len=a.length(),pos;
vector<string> b;
for(i=0;i<len;i++)
{
pos=a.find(c,i);
if(pos<len)
{
b.push_back(a.substr(i,pos-i));
i=pos;
}
}
return b;
}
int main()
{
string s="12,11,4";
vector<string> a=fenge2(s,',');
for(auto i:a)
cout<<i<<' ';
}
string字符串分割,并把数字子字符串转成int型,放入数组:
用到从c_str(),atoi()函数,字符串转换成int型 int k=atoi(str.substr(i,pos-i).c_str());
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;
typedef string::size_type sz;
int main()
{
string str="11,12,13,14";
string p=",";
str=str+p;
vector<int> a;
sz i,pos,len=str.size();
for(i=0;i<len;i++)
{
pos=str.find(p,i);
if(pos<len)
{
int k=atoi(str.substr(i,pos-i).c_str());
a.push_back(k);
i=pos;
}
}
for(int j:a)
cout<<j<<endl;
return 0;
}
原文链接: https://www.cnblogs.com/home123/p/6774909.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/253112
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!