C++字符串解析分享,求优化,该如何处理
C++字符串解析分享,求优化
需求:字符串“#C255 244 233 12# #d4# #f5 ,将其中的数字和字母分离出来,其中‘#’字符可能是别的字符
我自己写的比较繁琐,使用了C++的string类和VECTOR,当然使用c可能更高效一些,分享一下,求指教,如何才能写的更简洁。
需求:字符串“#C255 244 233 12# #d4# #f5 ,将其中的数字和字母分离出来,其中‘#’字符可能是别的字符
我自己写的比较繁琐,使用了C++的string类和VECTOR,当然使用c可能更高效一些,分享一下,求指教,如何才能写的更简洁。
#include "iostream"
#include "string"
#include "vector"
using namespace std;
//using namespace string;
const string const_str = "#C255 244 233 22##H5##a1#";
//检测##的位置以及数目
vector<int> GetTagPos(const string& str ,const string& tag)
{
vector<int> iPosList;
size_t tag_pos = 0 ;
size_t search_pos = 0;
size_t search_length = str.length();
iPosList.clear();
iPosList.reserve(32);
if(tag.empty() || str.empty())
goto _return;
while(search_pos <= search_length) //检测tag位置
{
if((tag_pos = str.find(tag,search_pos))!= string::npos )
{
iPosList.push_back(tag_pos);
search_pos = tag_pos + 1 ;
}
else
{
break;
}
}
if(iPosList.size()%2 != 0 ) //如果不配对,返回空
{
iPosList.clear();
goto _return;
}
_return:
return iPosList ;
}
void GetResult(const string& str , const string& tag )
{
size_t ipos = 0 ;
size_t word_pos = 0 ;
string strNum;
vector<int> itagpos;
if(true == str.empty())
return ;
itagpos = GetTagPos(str,tag);
if(itagpos.empty())
return ;
vector<int>::iterator it = itagpos.begin();
for( ; it != itagpos.end() ; ++ it) //首先检测字母
{
for(ipos = (*it) + 1 ; ipos != *(++it)+1 ; ++ipos)
{
char c = str[ipos] ;
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
cout << c << endl ;
word_pos = ipos ;
break;
}
else
{
continue ;
}
}