C++ 字符串分割,并把子字符串转换成int型整数

时间:2023-03-08 16:48:27

主要涉及到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",);
cout<<"s.find(b,5) is : "<<position<<endl; //查找s 中flag 出现的所有位置。
flag="a";
position=;
int i=;
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="";
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=,i,len=a.length();
for(i=;i<len;i++)
{
if(i==&&a[i]==c)
pos=i+;
else if(a[i]==c)
{
b.push_back(a.substr(pos,i-pos));
pos=i+;
}
else if(i==len-)
{
b.push_back(a.substr(pos,i-pos+));
}
}
return b;
} vector<string> fenge2(string a,char c)
{
a=a+c;
int i,len=a.length(),pos;
vector<string> b;
for(i=;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=;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 ;
}