M的字符串操作函数是我见过的最简单的。$p就是按指定分割符和位置取字串,非常方便。
类似下面:
s str="张三^29岁^男^433127199101211234"
s name=$p(str,"^",1)
s age=$p(str,"^",2)
s sex=$p(str,"^",3)
为了方便的使用C++操作字符串按此习惯包装系列M操作字符串接口
头文件
#pragma onece
#include <iostream>
#include <cstring>
using namespace std;
///用C++实现M常用操作字符串方法$改doler
///按指定字符串分割字符串取指定位置
///retStr:返回串
///source:源串
///split:分割串
///index:位置,按M习惯从1开始
///返回子串
void dolerp(string &retStr,string * source,string * split,int index);
cpp实现
#include "mutil.h"
///按指定字符串分割字符串取指定位置
///retStr:返回串
///source:源串
///split:分割串
///index:位置,按M习惯从1开始
///返回子串
void dolerp(string &retStr,string source,string split,int index)
{
retStr="";
//源串为空返回空
if(source=="")
{
return;
}
//分割串为空返回空
if(split=="")
{
return;
}
//位置不合格返回空
if(index<1)
{
return;
}
int sourceLen=source.length();
//源串为空返回空
if(sourceLen==0)
{
return;
}
int spLen=split.length();
//分割串为空返回空
if(spLen==0)
{
return;
}
int curIndex=0;
int startIndex=0;
int endIndex=0;
//遍历找到按分割串分割的指定位数的串
for(int i=0;i<sourceLen;i++)
{
//当前位置大于等于分割串长度,且当前字符等于分割串最后一位就比前面字符
if(i>=spLen&&source[i]==split[spLen-1])
{
//时候和分割串相同
bool isCommon=true;
for(int j=1;j<spLen;j++)
{
if(source[i-j]!=split[spLen-1-j])
{
isCommon=false;
break;
}
}
if(isCommon==true)
{
curIndex++;
if(curIndex==index)
{
endIndex=i-spLen;
break;
}
if(curIndex==index-1)
{
startIndex=i+1;
}
i+=spLen;
}
}
}
//不包含子串返回源串
if(curIndex==0&&index==1)
{
retStr=source;
return;
}
//没有取的位数返回空
else if(curIndex<index-1)
{
return;
}
else
{
if(startIndex>endIndex)
{
endIndex=sourceLen-1;
}
int retArrLen=endIndex-startIndex+1;
char retArr[retArrLen];
for(int k=startIndex;k<=endIndex;k++)
{
retStr+=source[k];
}
return;
}
}
///测试
int main(int argc, char* argv[])
{
string all="张三^29岁^男^433127199101211234";
string sp="^";
string ret;
dolerp(ret,all,sp,1);
cout<<"第一位为:"<<ret<<endl;
dolerp(ret,all,sp,2);
cout<<"第二位为:"<<ret<<endl;
dolerp(ret,all,sp,3);
cout<<"第三位为:"<<ret<<endl;
dolerp(ret,all,sp,4);
cout<<"第四位为:"<<ret<<endl;
dolerp(ret,all,"29",2);
cout<<"29分割第二位为:"<<ret<<endl;
dolerp(ret,all,"298",2);
cout<<"298分割第二位为:"<<ret<<endl;
dolerp(ret,all,"433",1);
cout<<"433分割第一位为:"<<ret<<endl;
return 0;
}
Cmake
# CMakeList.txt: mutil 的 CMake 项目,在此处包括源代码并定义
# 项目特定的逻辑。
#
cmake_minimum_required (VERSION 3.8)
project ("mutil")
# 将源代码添加到此项目的可执行文件。
add_executable (mutil "mutil.cpp" "mutil.h")
# TODO: 如有需要,请添加测试并安装目标。
效果
[zhanglianzhu@zlzlinux mutil]$
[zhanglianzhu@zlzlinux mutil]$ make
Consolidate compiler generated dependencies of target mutil
[100%] Built target mutil
[zhanglianzhu@zlzlinux mutil]$ make
[ 50%] Building CXX object CMakeFiles/mutil.dir/mutil.cpp.o
[100%] Linking CXX executable mutil
[100%] Built target mutil
[zhanglianzhu@zlzlinux mutil]$ ./mutil
第一位为:张三
第二位为:29岁
第三位为:男
第四位为:433127199101211234
29分割第二位为:岁^男^433127199101211234
298分割第二位为:
433分割第一位为:张三^29岁^男^
[zhanglianzhu@zlzlinux mutil]$
习惯习惯CentOS下的VSCode和Cmake开发